var inventory;
(function() { var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { var p = this;
            this.$timeout = n;
            this.inventoryUtil = t;
            this.dataDicSvc = i;
            this.$q = r;
            this.officeUtil = u;
            this.permissionProvider = f;
            this.$window = e;
            this.productSvc = o;
            this.inventorySvc = s;
            this.inventoryProductSvc = h;
            this.aresNotification = c;
            this.$document = l;
            this.aresModalShelf = a;
            this.enums = v;
            this.officeOptionSvc = y;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/components/sku-auto-complete-selector/sku-auto-complete-selector-view.html";
            this.scope = { options: "=", warehouseId: "=", onSelect: "&", onBrowseProduct: "&?", onProductCreated: "&?", onWithCountChange: "&?", skuModalInstance: "=?" };
            this.link = function(n, t, i) { var f = t.find("input"),
                    u = t.find(".product-list-content"),
                    c = !1,
                    h = [],
                    r = -1,
                    v = 0,
                    d = function(t) { if (n.keyword = "", n.searchMode = n.isProductUnicodeEnabled ? t : n.searchMode === "normal" ? "barcode" : "normal", n.searchMode === "barcode" || n.searchMode === "unicode") { var i = n.searchMode === "barcode" ? "请输入条形码" : "请输入唯一码";
                            f.attr("placeholder", i).focus();
                            o() } else f.attr("placeholder", "物品名称/拼首码/品牌/规格/内部编码/条形码").focus() },
                    g = function() { var t = []; return t.push(p.inventoryUtil.getProductCodeOptions().then(function(t) { return n.productCodeOptions = t, !0 })), n.options.mode === "takeOrder" && t.push(p.dataDicSvc.officeSettingDic.load().then(function(t) { return n.isInventoryOverflowTakeEnabled = t.isInventoryOverflowTakeEnabled, !0 })), n.options.mode === "takeOrder" || n.options.mode === "outOrder" || n.options.mode === "checkOrder" || n.options.mode === "quotation" ? n.canCreateSpu = !1 : t.push(p.officeUtil.isRootGroup().then(function(t) { return n.canCreateSpu = t && p.permissionProvider.isAllowed("product.productInfo"), !0 })), n.searchMode = "normal", n.options.withCount = n.options.mode === "takeOrder" || n.options.mode === "outOrder" || n.options.mode === "checkOrder" ? !0 : !1, n.options.mode === "outOrder" || n.options.mode === "checkOrder" || n.options.mode === "inOrder" ? t.push(p.officeOptionSvc.getOfficeOption(p.officeOptionSvc.optionKeys.IsProductUnicodeManagementEnabled).then(function(t) { n.isProductUnicodeEnabled = t })) : n.isProductUnicodeEnabled = !1, n.options.mode === "procurement" ? n.createSpuTabIndex = 2 : n.options.mode === "inOrder" && (n.createSpuTabIndex = 1), p.$q.all(t).then(function() { return !0 }) },
                    y = function() { u.data("mCustomScrollbarIndex") ? (u.mCustomScrollbar("update"), u.mCustomScrollbar("scrollTo", "top")) : u.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) },
                    e, nt = function() { var i = 140;
                        n.productCodeOptions.allowInsideCode || (i += 70);
                        n.productCodeOptions.allowFirmCode || (i += 60);
                        n.baseWidth = i;
                        e = angular.element(p.$window).height() - f.offset().top - 300;
                        e = Math.floor(e / 32) * 32;
                        u.height(e);
                        y();
                        f.on("compositionstart", function() { c = !0 }).on("compositionend", function() { c = !1 });
                        p.$timeout(function() { var n = t.find("#skuAutoCompleteModeDropdown");
                            n.on("show.bs.dropdown", function() { o() }) }, 0, !1) },
                    w = function(n) { var t = angular.element(n.target);
                        t.closest(".sku-auto-complete-dropdown").length !== 0 || t.hasClass("sku-auto-complete-selector-input") || t.closest(".sku-auto-complete-bar-code-switch").length !== 0 || o() },
                    o = function() { p.$timeout(function() { n.isOpen = !1 });
                        angular.element(p.$document).off("click", w) },
                    b = function() { if (!s()) { n.isOpen = !0;
                            n.products && n.products[0] && (r = 0, n.activeProductId = n.products[0].id);
                            angular.element(p.$document).on("click", w);
                            p.$timeout(function() { y() }, 0, !1) } },
                    tt = function(t) { var r = p.$q.defer(),
                            i = { pageIndex: 1, pageSize: 50, searchText: t, isOnlyLinkedCare: n.options.isLinkedCare }; return n.options.isCheckInventoryLog && (i.isCheckInventoryLog = !0), n.options.isOnlyEnabled && (i.isOnlyEnabled = !0), n.options.mode === "takeOrder" && (i.isInventoryTake = !0), p.productSvc.searchProducts(i).success(function(n) { var t = n.items;
                            t.forEach(function(n) { n.productId = n.id });
                            r.resolve(t) }), r.promise },
                    it = function(t) { var r = p.$q.defer(),
                            i = { pageIndex: 1, pageSize: 50, searchText: t }; return (n.options.mode === "outOrder" || n.options.mode === "checkOrder") && (i.warehouseId = n.warehouseId, n.options.mode === "checkOrder" && (i.IncludeZeroCount = !0)), n.options.mode === "takeOrder" && (i.isInventoryTake = !0), p.inventoryProductSvc.searchLiteInventoryProduct(i).success(function(n) { var t = n.items;
                            t.forEach(function(n) { n.id = n.productId });
                            r.resolve(t) }), r.promise },
                    rt = function(t) { var i = p.$q.defer(),
                            r = { pageIndex: 1, pageSize: 1, producerBarCode: t, IsOnlyLinkedCare: n.options.isLinkedCare }; return p.productSvc.searchProducts(r).success(function(n) { if (n.items && n.items.length !== 0) { var t = n.items[0];
                                t.productId = t.id;
                                i.resolve(t) } else i.reject("找不到条形码对应的物品");
                            f.val("") }), i.promise },
                    ut = function(t) { var r = p.$q.defer(),
                            i = { pageIndex: 1, pageSize: 1 },
                            u; return n.searchMode === "barcode" ? (i.producerBarCode = t, u = "条形码对应的物品没有库存") : n.searchMode === "unicode" && (i.unicode = t, u = "唯一码对应的物品没有库存"), n.warehouseId && (i.warehouseId = n.warehouseId), n.options.mode === "takeOrder" && (i.isInventoryTake = !0), n.options.mode == "checkOrder" && (i.includeZeroCount = !0), n.options.includeZeroCount && (i.includeZeroCount = !0), p.inventoryProductSvc.searchLiteInventoryProduct(i).success(function(n) { if (n && n.items && n.items.length !== 0) { var t = n.items[0];
                                r.resolve(t) } else r.reject(u);
                            f.val("") }), r.promise },
                    k = function() { if (!c) { if (!n.keyword && (!n.warehouseId || n.warehouseId == v) && h && h.length > 0) { n.products = h;
                                b(); return } var t;
                            t = n.options.withCount ? it : tt;
                            t(n.keyword).then(function(t) { n.products = t;
                                n.keyword || (h = t);
                                n.warehouseId || (v = n.warehouseId);
                                b() }) } },
                    ft = function(i) { if (i.keyCode === p.enums.KeyCode.Enter || i.key === "Enter")
                            if (n.keyword = i.target.value, s() && n.keyword) { if (n.options.mode === "inOrder" && n.searchMode === "unicode" && !n.options.includeZeroCount) { p.aresNotification.error("当前入库类型不支持唯一码扫码模式"); return } var f = void 0;
                                f = n.options.withCount || n.options.includeZeroCount ? ut : rt;
                                f(n.keyword).then(function(t) { p.$timeout(function() { n.onSelect({ selectedProduct: t, barCodeMode: n.searchMode, unicode: n.keyword }) }) }, function(n) { p.aresNotification.error(n) }) } else !s() && n.isOpen ? r > -1 ? a(n.products[r]) : a(n.products[0]) : s() || n.isOpen || k();
                        else i.keyCode === p.enums.KeyCode.Up || i.key === "Up" ? (i.preventDefault(), r > 0 && r <= n.products.length - 1 ? (r--, n.activeProductId = n.products[r].id) : (r = n.products.length - 1, n.activeProductId = n.products[n.products.length - 1].id), p.$timeout(function() { var i, f; if (r === n.products.length - 1) u.mCustomScrollbar("scrollTo", r * 32);
                            else { if (i = t.find(".product-row[data-product-id=" + n.activeProductId + "]"), f = i.closest(".mCSB_container")[0], i.length === 0 || f.length === 0) return; var e = i[0].offsetTop,
                                    o = i.closest(".mCSB_container")[0].offsetTop,
                                    s = Math.floor(e / 32);
                                e + o < 0 && u.mCustomScrollbar("scrollTo", s * 32) } }, 0, !1)) : i.keyCode === p.enums.KeyCode.Down || i.key === "Down" ? (i.preventDefault(), r > -1 && r < n.products.length - 1 ? (r++, n.activeProductId = n.products[r].id) : (r = 0, n.activeProductId = n.products[0].id), p.$timeout(function() { var i, f; if (r === 0) u.mCustomScrollbar("scrollTo", 0);
                            else { if (i = t.find(".product-row[data-product-id=" + n.activeProductId + "]"), f = i.closest(".mCSB_container"), i.length === 0 || f.length === 0) return; var o = i[0].offsetTop,
                                    s = f[0].offsetTop,
                                    h = Math.floor(o / 32);
                                o + s > e - 32 && u.mCustomScrollbar("scrollTo", (h + 1) * 32 - e) } }, 0, !1)) : (i.keyCode === p.enums.KeyCode.Esc || i.key === "Esc") && o() },
                    l = function(t) { if (n.options.withCount && n.warehouseId == -1) { p.aresNotification.error("寄售仓库请选择供应商"); return } var i; switch (n.options.mode) {
                            case "procurement":
                                if (n.skuModalInstance && !n.skuModalInstance.destroyed) { n.skuModalInstance.switchTab(t); return } i = [{ title: "物品一览", titleIconClass: "iconfont icon-wpml", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "productListWithoutCount" } } }, setDefault: t === 0, needActive: !1 }, { title: "历史采购", titleIconClass: "iconfont icon-shijian", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "historyProcurement" } } }, setDefault: t === 1, needActive: !1 }];
                                n.canCreateSpu && i.push({ title: "新增物品", titleIconClass: "iconfont icon-addition", template: "<spu-edit-basic-view><\/spu-edit-basic-view>", controller: "SpuEditBasicCtrl", setDefault: t === 2, needActive: !0, resolve: { host: function() { return {} } }, confirmClose: !0 });
                                n.skuModalInstance = p.aresModalShelf.open({ tabs: i });
                                n.skuModalInstance.result.then(function() { p.$timeout(function() { l(0) }, 1e3, !1) }); break;
                            case "takeOrder":
                                if (n.skuModalInstance && !n.skuModalInstance.destroyed) { n.skuModalInstance.switchTab(t); return } i = [{ title: "物品一览", titleIconClass: "iconfont icon-wpml", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "takeOrderList", withCount: n.options.withCount } } }, setDefault: t === 0, needActive: !1 }, { title: "历史领用", titleIconClass: "iconfont icon-shijian", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "historyTakeOrder" } } }, setDefault: t === 1, needActive: !1 }];
                                n.skuModalInstance = p.aresModalShelf.open({ tabs: i }); break;
                            case "inOrder":
                                if (n.skuModalInstance && !n.skuModalInstance.destroyed) { n.skuModalInstance.switchTab(t); return } i = [{ title: "物品一览", titleIconClass: "iconfont icon-wpml", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "inOrder", isCheckInventoryLog: !1 } } }, setDefault: t === 0, needActive: !1 }];
                                n.canCreateSpu && i.push({ title: "新增物品", titleIconClass: "iconfont icon-addition", template: "<spu-edit-basic-view><\/spu-edit-basic-view>", controller: "SpuEditBasicCtrl", setDefault: t === 1, needActive: !0, resolve: { host: function() { return {} } }, confirmClose: !0 });
                                n.skuModalInstance = p.aresModalShelf.open({ tabs: i });
                                n.skuModalInstance.result.then(function() { p.$timeout(function() { l(0) }, 1e3, !1) }); break;
                            case "outOrder":
                                if (n.skuModalInstance && !n.skuModalInstance.destroyed) { n.skuModalInstance.switchTab(t); return } i = [{ title: "物品一览", titleIconClass: "iconfont icon-wpml", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "outOrder", withCount: !0, warehouseId: n.warehouseId } } }, setDefault: t === 0, needActive: !1 }];
                                n.skuModalInstance = p.aresModalShelf.open({ tabs: i }); break;
                            case "checkOrder":
                                if (n.skuModalInstance && !n.skuModalInstance.destroyed) { n.skuModalInstance.switchTab(t); return } i = [{ title: "物品一览", titleIconClass: "iconfont icon-wpml", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "checkOrder", withCount: !0, warehouseId: n.warehouseId } } }, setDefault: t === 0, needActive: !1 }];
                                n.skuModalInstance = p.aresModalShelf.open({ tabs: i }); break;
                            case "quotation":
                                if (n.skuModalInstance && !n.skuModalInstance.destroyed) { n.skuModalInstance.switchTab(t);
                                    p.aresModalShelf.broadcast("SWITCH_SKU_SELECT_TYPE", { type: "quotation" }); return } i = [{ title: "添加规格", titleIconClass: "iconfont icon-wpml", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "quotation" } } }, setDefault: t === 0, needActive: !1 }];
                                n.skuModalInstance = p.aresModalShelf.open({ tabs: i }) } },
                    et = function() { if (angular.isDefined(i.onWithCountChange)) n.onWithCountChange({ withCount: n.options.withCount }) },
                    a = function(t) { n.onSelect({ selectedProduct: angular.copy(t), barCodeMode: s() });
                        n.keyword = "";
                        o() },
                    s = function() { return n.searchMode === "barcode" || n.searchMode === "unicode" };
                (function() { n.isOpen = !1;
                    n.keyword = "";
                    n.searchMode = "normal";
                    n.onSwitchSearchMode = d;
                    n.loadProducts = k;
                    n.openSkuSelectModal = l;
                    n.onWithCountChangeWrapper = et;
                    n.onSelectWrapper = a;
                    n.onKeyUp = ft;
                    g().then(function() { nt() }) })() } } return n.$inject = ["$timeout", "inventoryUtil", "dataDicSvc", "$q", "officeUtil", "permissionProvider", "$window", "productSvc", "inventorySvc", "inventoryProductSvc", "aresNotification", "$document", "aresModalShelf", "enums", "officeOptionSvc"], n }();
    supplychainModule.directive("skuAutoCompleteSelectorView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
supplychainModule.directive("skuBatchExpireDropdown", ["$timeout", "$compile", "$window", "$document", "$q", "toFormatPriceFilter", "inventorySvc", function(n, t, i, r, u, f, e) { "use strict"; return { restrict: "E", scope: { sku: "=", warehouseId: "=", selectedBatch: "=", selectedExpire: "=", selectedUnicode: "=", onSelect: "&", mode: "=" }, templateUrl: "/app/supplychain/components/sku-batch-expire-dropdown/sku-batch-expire-dropdown-view.html", replace: !0, link: function(t, r) { var f, o = r.find(".sku-batch-expire-dropdown-anchor"),
                h = function() { n(function() { var n = f.find(".sku-batch-expire-popover-body-wrapper");
                        n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                        f.find(".sku-batch-expire-popover-search-input input").focus() }, 0, !1) },
                c = function() { var u, n, r, e;
                    (f = o.data("bs.popover").$tip, f.find(".arrow").remove(), u = 0, n = t.currentBatchExpires.recent && t.currentBatchExpires.recent.length, n) && (n = n > 6 ? 6 : n, r = n * 28 + 32 + 32, angular.element(i).height() - o.offset().top - 32 < r && (u = -32 - r), e = o.width(), f.css({ padding: 0, border: 0, marginLeft: 134 - e / 2 + "px", marginTop: u + "px", background: "transparent", boxShadow: "none", height: r + "px", minHeight: "unset" })) },
                l = function() { t.batchExpireSearch.text = "";
                    a().then(function() { t.filteredBatchExpires = t.currentBatchExpires.recent;
                        n(function() { o.popover("show");
                            h() }) }) },
                a = function() { var i, n; return t.sku.batchAndExpires ? i = u.when(t.sku.batchAndExpires) : (n = u.defer(), i = n.promise, e.getRecentOutedBatchAndExpireByProductIds([t.sku.productId], t.warehouseId).success(function(i) { var r = _.find(i, function(n) { return n.productId === t.sku.productId });
                        r && r.items ? n.resolve({ recent: r.items, all: r.allItems }) : n.resolve([]) })), i.then(function(n) { var i = !1;
                        _.each(n.recent, function(n) { n.expiredDate && (n.expiredDate = s(n.expiredDate));
                            n.isActive = n.expiredDate == t.selectedExpire && n.batchNumber == t.selectedBatch && n.unicode == t.selectedUnicode;
                            i = i || !!n.unicode });
                        _.each(n.all, function(n) { n.expiredDate && (n.expiredDate = s(n.expiredDate));
                            n.isActive = n.expiredDate == t.selectedExpire && n.batchNumber == t.selectedBatch && n.unicode == t.selectedUnicode;
                            i = i || !!n.unicode });
                        t.isUnicodeVisible = i;
                        t.popoverWidth = i ? 550 : 280;
                        t.popoverSearchPlaceholder = i ? "搜索批号/有效期/唯一码" : "搜索批号/有效期";
                        t.currentBatchExpires = n;
                        t.sku.batchAndExpires = t.currentBatchExpires }) },
                v = function(n) { if (angular.isDefined(t.onSelect)) t.onSelect({ batchAndExpire: n });
                    o.popover("hide") },
                y = function() { t.filteredBatchExpires = t.batchExpireSearch.text ? _.filter(t.currentBatchExpires.all, function(n) { return n.batchNumber && n.batchNumber.indexOf(t.batchExpireSearch.text) > -1 || n.expiredDate && n.expiredDate.indexOf(t.batchExpireSearch.text) > -1 || n.unicode && n.unicode.indexOf(t.batchExpireSearch.text) > -1 }) : t.currentBatchExpires.recent;
                    h() },
                s = function(n) { return n ? moment(n).format("YYYY-MM-DD") : n };
            (function() { t.batchExpireSearch = { text: "" };
                t.showPopover = l;
                t.onShowPopover = c;
                t.onSelectedWrapper = v;
                t.onSearchTextChange = y;
                t.$watch("selectedExpire", function(n) { n && (t.selectedExpire = s(n)) }) })() } } }]);
supplychainModule.directive("skuSupplierPriceDropdown", ["$timeout", "$compile", "$window", "$document", "$q", "toFormatPriceFilter", "productSvc", "enums", "officeUtil", "permissionProvider", "officeOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c) { "use strict"; return { restrict: "E", scope: { sku: "=", selectedDealerName: "=", onSelect: "&", mode: "=?", dealerCounts: "=?", onConfirm: "&?" }, templateUrl: "/app/supplychain/components/sku-supplier-price-dropdown/sku-supplier-price-dropdown-view.html", link: function(t, r, l) { var v, a = r.find(".sku-supplier-price-dropdown-anchor"),
                p = function() { n(function() { var n = v.find(".sku-supplier-price-popover-body-wrapper");
                        n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                        v.find("sku-supplier-price-popover-search-input input").focus() }, 0, !1) },
                b = function() { var u, n, r;
                    _.each(t.currentProductSuppliers, function(n) { n.isEdit = !1 });
                    t.countData = angular.copy(t.dealerCounts);
                    v = a.data("bs.popover").$tip;
                    v.find(".arrow").remove();
                    u = 0;
                    n = t.currentProductSuppliers && t.currentProductSuppliers.length || 0;
                    n = n > 6 ? 6 : n;
                    r = n * 28 + 32 + 32;
                    t.editCount && (r += 32);
                    angular.element(i).height() - a.offset().top - 32 < r && (u = (t.mode === "input" ? -32 : -22) - r);
                    v.css({ padding: 0, border: 0, marginLeft: t.mode === "input" ? "60px" : t.editCount ? "-162px" : "-130px", marginTop: u + "px", background: "transparent", boxShadow: "none", height: r + "px", minHeight: "unset", maxWidth: "unset", width: t.editCount ? "345px" : "280px" });
                    p() },
                k = function() { t.editSupplierSearch.text = "";
                    d().then(function() { t.filteredProductSuppliers = y(_.clone(t.currentProductSuppliers));
                        n(function() { a.popover("show") }) }) },
                y = function(n) { var t = _.filter(n, function(n) { return n.price > 0 }),
                        i = _.filter(n, function(n) { return !(n.price > 0) }); return [].concat(w(t)).concat(w(i)) },
                w = function(n) { var t = [],
                        r = _.find(n, function(n) { return n.isPreferred }),
                        i, u; return r && t.push(r), i = _.filter(n, function(n) { return (n.dealerType === o.OrganizationType.LinkedCare || n.dealerType === o.OrganizationType.MallDealer) && !n.isPreferred }), i && (t = t.concat(i)), u = _.filter(n, function(n) { return n.dealerType === o.OrganizationType.NormalDealer && !n.isPreferred }), t.concat(u) },
                d = function() { var n, i; return _.isArray(t.sku.dealers) ? (t.sku.dealers = y(t.sku.dealers), n = u.when(t.sku.dealers)) : (i = u.defer(), e.getProductDealers(t.sku.productId).success(function(n) { i.resolve(n) }), n = i.promise), n.then(function(n) { t.isProcurementPriceLockEnabled && !t.editProductPermission && (n = _.filter(n, function(n) { return n.price > 0 }));
                        _.each(n, function(n) { n.priceStr = n.price > 0 ? f(n.price) : "无" });
                        t.currentProductSuppliers = n;
                        t.sku.dealers = n }) },
                g = function(n) { if (angular.isDefined(t.onSelect)) t.onSelect({ dealer: n });
                    a.popover("hide") },
                nt = function() { t.filteredProductSuppliers = y(_.filter(t.currentProductSuppliers, function(n) { return n.dealerName.indexOf(t.editSupplierSearch.text) > -1 }));
                    p() },
                tt = function() { s.isRootGroup().then(function(n) { t.editProductPermission = n && h.isAllowed("product.productInfo") });
                    c.getOfficeOption(c.optionKeys.IsProcurementPriceLockEnabled).then(function(n) { t.isProcurementPriceLockEnabled = n }) },
                it = function(t, i) { i.stopPropagation();
                    t.isEdit || (t.isEdit = !0, n(function() { var n = angular.element(i.currentTarget).find("input");
                        n.focus();
                        angular.isFunction(n[0].select) && n[0].select() }, 0, !1)) },
                rt = function() { a.popover("hide") },
                ut = function() { if (t.countData && angular.isDefined(l.onConfirm)) { var n = {};
                        _.each(t.countData, function(i, r) { var u = _.find(t.currentProductSuppliers, function(n) { return n.dealerId == r });
                            u && (n[r] = { dealerId: u.dealerId, dealerCode: u.dealerCode, dealerType: u.dealerType, dealerName: u.dealerName, settlementMethod: u.settlementMethod, price: u.price, count: i }) });
                        t.onConfirm({ data: n }) } a.popover("hide") };
            (function() { t.mode || (t.mode = "input");
                t.editCount = !!t.dealerCounts;
                t.editSupplierSearch = { text: "" };
                t.showSupplierPopover = k;
                t.onShowSupplierPopover = b;
                t.onDealerSelectedWrapper = g;
                t.onEditSupplierSearchTextChange = nt;
                t.enableEdit = it;
                t.cancel = rt;
                t.confirm = ut;
                tt() })() } } }]);
supplychainModule.directive("spuImageMagnifier", ["$window", function(n) { "use strict"; return { restrict: "A", link: function(t, i, r) { var u = function() { i.on("mouseover", function() { var e = i.parent(),
                        o = i.offset().top,
                        t = i.height(),
                        s = angular.element(n).height(),
                        u, f;
                    u = o + t + 248 > s ? -248 : 0 - t;
                    f = angular.element("<img>").attr("src", r.src).css({ width: "248px", height: "248px", position: "relative", top: u + "px", left: 0, "z-index": 1, background: "#fff", border: "1px solid #CFDBDD", "box-shadow": "0 1px 20px 0 rgba(0,0,0,0.20)" }).appendTo(e).on("mouseout", function() { f.remove() }) }) };
            (function() { u() })() } } }]);
supplychainModule.controller("InventorySystemItemEditCtrl", ["$log", "$scope", "$modalInstance", "aresConfirmDialog", "aresNotification", "systemitemSvc", "dataDicSvc", "host", function(n, t, i, r, u, f, e, o) { "use strict";
    t.cancel = function() { i.dismiss("cancel") };
    t.saveSystemItem = function() { t.currentSystemItem.itemName = t.currentSystemItem.itemName.replace(/\s/g, ""); var n = _.some(t.siblings, function(n) { return n.itemName === t.currentSystemItem.itemName && n.id !== t.currentSystemItem.id }); if (n) { r.warn({ message: "已经有其他项目使用此名称，请更换新名称！" }); return } f.updateSystemItem(t.currentSystemItem).success(function(n) { u.success("保存成功！");
                i.close(n) }).error(function(n) { n.name === "SystemItemNameNotUniqueException" && r.warn({ message: "已经有其他项目使用此名称，请更换新名称！" }) }) },
        function() { t.currentSystemItem = o.currentSystemItem;
            t.siblings = o.siblings;
            t.dataTypeName = o.dataTypeName }() }]);
supplychainModule.controller("WarehouseEditCtrl", ["$log", "$scope", "$q", "$modalInstance", "$modal", "warehouseSvc", "dataDicSvc", "dataHost", "loginContext", "aresNotification", "enums", "eventAggregator", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; var v = { isDefault: !1, isInactive: !1, grade: c.WarehouseGrade.Office.value },
        y = function(n) { if (Ares.ensureNotDuplicated("SaveWarehouse")) { if (n.isDefault && n.isInactive) { h.error("主仓库不能设置为未启用！"); return } if (n.skuCount > 0 && n.isInactive) { h.error("当前仓库不为空，不能设置为未启用！"); return } if (s.roleType != "公司管理员" && t.warehouse.grade == c.WarehouseGrade.Company.value) { h.error("不能创建公司仓库!"); return } var i = a() ? f.update : f.add;
                i(n).then(function(n) { e.warehouseDic.refresh();
                    l.publish(l.events.WarehouseEdited, null, "WarehouseEditCtrl");
                    r.close(n);
                    Ares.sensors.track("WarehouseEditCtrl", { PatientName: t.warehouse.name, OperationType: "确定" }) }) } },
        p = function() { var n = o.warehouse;
            n && n.id ? f.get(n.id).success(function(n) { n.disabled = n.grade === c.WarehouseGrade.Consignee.value;
                t.warehouse = n;
                t.warehouse.skuCount = o.warehouse.skuCount }) : (n = n || angular.copy(v), n.disabled = !1, t.warehouse = n) },
        a = function() { return !!t.warehouse.id },
        w = function() { r.dismiss("close") };
    (function() { t.isEdit = a;
        t.saveWarehouse = y;
        t.close = w;
        t.disableOffice = !1;
        p() })() }]);
supplychainModule.controller("WareHouseListCtrl", ["$log", "$scope", "$modal", "warehouseSvc", "aresConfirmDialog", "dataDicSvc", "aresNotification", "userOptionSvc", "$q", "gridOptionUtil", "loginContext", "officeSvc", "enums", "userSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a) { "use strict";
    t.searchCriteria = { isSearchInventory: !0 }; var y = function() { p().then(function() { l.getOfficeList().then(function(n) { t.offices = n;
                    w() }) }) },
        p = function() { var n = s.defer(); return o.getUserOption(h.keys.warehouseGridOption).then(function(i) { t.showColumns = i != null ? i : [];
                n.resolve(!0) }), n.promise },
        w = function() { t.searchCriteria.isInactive = !t.searchIsActive;
            r.searchWarehouses(t.searchCriteria).success(function(n) { var i = !1;
                _.forEach(n, function(n) { var u = _.find(t.offices.data, function(t) { return t.id == n.officeId }),
                        r;
                    n.officeName = u ? u.name : "";
                    n.gradeStr = n.grade == a.WarehouseGrade.Company.value ? a.WarehouseGrade.Company.name : a.WarehouseGrade.Office.name;
                    i || (i = n.availableOffices && n.availableOffices.length > 2);
                    n.availableOffices && n.availableOffices.length !== 0 ? (r = [], _.forEach(n.availableOffices, function(n) { n && r.push(n.name) }), n.availableOfficesStr = r.join(",")) : n.availableOfficesStr = n.officeName });
                t.warehouses = n;
                t.selectedWarehouse = null;
                t.sharedWarehouseExists = i }) },
        it = function(n) { var i = [];
            formatUtil.formatList(n, { isInUse: "boolStr" }, function(n) { i.indexOf(n.category) < 0 && i.push(n.category) });
            t.categories = i },
        k = function(n) { n && (t.toBeSelectedWarehouseId = n.id);
            y() },
        rt = function() { r.searchWarehouses(t.searchCriteria).success(function(n) { t.warehouses = n }) },
        d = function() { b(null).then(function(n) { v(n) }) },
        g = function(n) { b(n).then(function(n) { v(n) }) },
        b = function(n) { var t = i.open({ animation: !0, backdrop: "static", template: "<warehouse-edit-view><\/warehouse-edit-view>", controller: "WarehouseEditCtrl", windowClass: "warehouse-edit-view-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { dataHost: function() { return { warehouse: n } } } }); return t.result },
        nt = function(n) { var t = n.name;
            u.warn({ message: "确认要删除仓库【" + t + "】？", showCancelBtn: !0 }).then(function() { r.destroy(n.id).success(function() { v();
                    f.warehouseDic.refresh();
                    e.success("仓库【" + t + "】已删除") }).error(function(n) { n.name === "WarehouseInventoryProductException" && e.error("仓库删除失败，" + n.message) }) }) },
        v = function(n) { k(n) },
        ut = function(n) { var i, u, f; if (t.selectedWarehouse && (i = t.warehouses, u = _.findIndex(i, { id: t.selectedWarehouse.id }), u > -1)) { if (f = u + n, f < 0 || f >= i.length) return; var e = i[u],
                    o = i[f],
                    s = { firstWarehouseId: e.id, secondWarehouseId: o.id };
                r.exchangeShowOrder(s).success(function() { v(e) }) } },
        tt = function(n) { n && o.setUserOption(h.keys.warehouseGridOption, n) };
    (function() { t.query = w;
        t.addWarehouse = d;
        t.editWarehouse = g;
        t.deleteWarehouse = nt;
        t.updateColumnsOption = tt;
        t.loadColumnsOption = p;
        t.searchIsActive = !0;
        y() })() }]);
supplychainModule.controller("InventoryApplyOrderHomeCtrl", ["$log", "$scope", "aresNotification", "inventorySvc", "eventAggregator", "tenantSvc", function(n, t, i, r, u, f) { "use strict"; var e = [new Ares.TabItem("supplychain.myApply.takeOrderList", "领用申请单", null, null, undefined, undefined), ],
        o = function() { f.GetTenantIsCustomizeOpen().then(function(n) { n.data || (t.commands = [], t.commands.push(new Ares.TabCommand('<i class="iconfont icon-wenhao"><\/i>帮助', s, "lc-btn lc-btn-cyan lc-btn-icon lc-btn-icon-narrow", 0))) }) },
        s = function() { u.publish(u.events.HelpSlideToggled, {}, "InventoryApplyOrderHome") };
    (function() { t.states = e;
        o() })() }]);
supplychainModule.controller("InventoryTakeOrderListCtrl", ["$log", "$q", "$timeout", "$scope", "aresNotification", "inventorySvc", "$sce", "enums", "dataDicSvc", "reportUtil", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var c = function() { var n = angular.copy(r.searchCriteria),
                i; return n.status == "all" && (n.status = null), n.startDate = moment(n.startDate).format("YYYY-MM-DD"), n.endDate = moment(n.endDate).add(1, "days").format("YYYY-MM-DD"), i = t.defer(), f.searchTakeOrder(n).then(function(n) { var t = n.data;
                _.each(t.items, function(n) { n.statusHtml = v(n);
                    n.isCanCancel = y(n);
                    n.isCanEdit = p(n);
                    n.isCanReApply = w(n);
                    n.isCanSubmitWorkflow = l(n, !0);
                    n.isCanSubmitOrder = l(n, !1) });
                r.takeOrderList = t.items;
                r.takeOrderTotalCount = t.totalCount;
                i.resolve() }), i.promise },
        v = function(n) { var t; switch (n.status) {
                case 0:
                    t = '<label class="label label-warning">待提交<\/label>'; break;
                case 1:
                    t = '<label class="label label-warning">待审批<\/label>'; break;
                case 2:
                    t = '<label class="label label-warning">待处理<\/label>'; break;
                case 3:
                    t = '<label class="label label-success">已处理<\/label>'; break;
                case 4:
                    t = '<label class="label label-danger" data-toggle="tooltip" data-placement="bottom" style="cursor: pointer;" title="审批不通过原因：' + n.workflowRejectedNotes + '" data-viewport=".take-order-list-item">已拒绝 <i class="iconfont icon-xinxi" style="font-size: 12px;"><\/i><\/label>'; break;
                case 5:
                    t = '<label class="label label-default">已作废<\/label>'; break;
                case 6:
                    t = '<label class="label label-warning">部分处理<\/label>'; break;
                default:
                    t = '<label class="label label-default">未知<\/label>' } return e.trustAsHtml(t) },
        y = function(n) { return n.status === o.InventoryApplicationStatus.WaitPend || n.status === o.InventoryApplicationStatus.WaitHandle },
        p = function(n) { return n.status === o.InventoryApplicationStatus.WaitPend },
        w = function(n) { return !n.chargeOrderDetailId },
        l = function(n, t) { return n.status != o.InventoryApplicationStatus.WaitPend ? !1 : t ? r.inventoryTakeOrderWorkflow : !r.inventoryTakeOrderWorkflow },
        b = function(n) { var i = t.defer(); return f.cancelTakeOrder(n).then(function() { u.success("作废成功");
                i.resolve() }), i.promise },
        k = function() { d();
            s.workflowDefinitionDic.load().then(function(n) { return r.inventoryTakeOrderWorkflow = _.find(n, function(n) { return n.workflowType == o.WorkflowType.InventoryTake && !n.isDisabled == !0 }), c() }).then(function() { i(function() { r.initTableView() }) }) },
        d = function() { var n = h.getDefaultTimeSpan().startTime,
                t = h.getDefaultTimeSpan().endTime;
            r.searchTimeRange = { startDate: n, endDate: t };
            r.searchCriteria = { startDate: n, endDate: t, status: "all", orderNumber: "", pageIndex: 0, pageSize: 10 } },
        a = function(n) { var i = t.defer(); return f.getTakeOrder(n).then(function(n) { i.resolve(n.data) }), i.promise },
        g = function(n) { var i = t.defer(); return a(n.id).then(function(n) { n.status = o.InventoryApplicationStatus.WaitHandle;
                f.updateTakeOrder(n).then(function() { u.success("提交成功");
                    i.resolve() }) }), i.promise },
        nt = function(n) { var i = t.defer(); return a(n.id).then(function(n) { n.status = o.InventoryApplicationStatus.Pending;
                f.startWorkflowTakeOrder(n).then(function(n) { var t = n.data;
                    u.success("审批提交成功");
                    i.resolve() }).catch(function(n) { var t = n.data;
                    u.error("审批提交失败") }) }), i.promise };
    (function() { r.InventoryApplicationStatus = o.InventoryApplicationStatus;
        r.searchTakeOrder = c;
        r.cancelTakeOrder = b;
        r.submitHandleTakeOrder = g;
        r.submitWorkflowTakeOrder = nt;
        k() })() }]);
supplychainModule.controller("InventoryGroupProcurementApplyListCtrl", ["$scope", "$q", "inventoryUtil", "officeSvc", "officeSelectorUtil", "loginContext", "reportUtil", "enums", "procurementApplyOrderSvc", "moduleOptionProvider", "officeOptionSvc", "tenantOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; var a = function() { n.currentApply = null;
            n.activeIndex = -1; var r = t.defer(),
                i = _.clone(n.searchCriteria); return i.pageSize = n.page.pageSize, i.pageIndex = n.page.pageIndex, i.IsGetAllShareOffice = i.officeIds.length === 0, n.state === 0 ? i.IsGetPreHandled = !0 : i.status = o.ProcurementApplyStatus.Completed, i.endDate && (i.endDate = moment(i.endDate).add(1, "days").format("YYYY-MM-DD")), s.search(i).success(function(t) { if (_.each(t.items, function(n) { n.applyDate = moment(n.applyTime).format("YYYY-MM-DD") }), n.pageData = t, n.page.totalCount = n.pageData.totalCount, n.page.pageCount = n.pageData.pageCount || 1, t.items && t.items.length > 0) n.onSelectApply(t.items[0], 0);
                r.resolve(!0) }), r.promise },
        v = function() { return i.getProductCodeOptions().then(function(t) { n.productCodeOptions = t }) },
        y = function() { r.getSelfAndChildOfficesByGroupId(f.officeId, !1).success(function(t) { n.officeTreeData = u.setId(t); var i = _.filter(_.values(u.flattenToMap(t)), function(n) { return !n.isGroup });
                n.searchCriteria.officeIds = _.pluck(i, "officeId") }) },
        p = function() { var t = e.getDefaultTimeSpan();
            n.state = 0;
            n.page = { pageIndex: 1, pageSize: 20 };
            n.searchCriteria = { startDate: "", endDate: "", orderNo: null, officeIds: [] } },
        w = function(n) { return s.updateStatus(n, o.ProcurementApplyStatus.Completed) },
        b = function() { c.getOfficeOption("isGroupInventoryEnabled").then(function(t) { t === "1" || t === !0 ? l.getTenantOption("IsAcrossOfficeInventoryTransferEnabled").then(function(t) { n.isAcrossOfficeInventoryTransferEnabled = t }) : n.isAcrossOfficeInventoryTransferEnabled = !1 }) },
        k = function() { return i.getGroupProcurementConfigs().then(function(t) { return n.groupSalesEnabled = t.groupSalesEnabled, !0 }) },
        d = function() { return i.checkCanEditProcurementPrice().then(function(t) { return n.checkCanEditProcurementPrice = t, !0 }) },
        g = function() { return p(), v(), y(), b(), d(), k() },
        nt = function() { var t = ["内部编码", "名称", "品牌", "规格", "单位", "库存数", "申请数", "已发数", "待发数"],
                i = [{ width: 120 }, { width: 120 }, { width: 120 }, { width: 120 }, { width: 120 }, { width: 60 }, { width: 60 }, { width: 60 }, { width: 60 }],
                u, r, f, e;
            n.productCodeOptions.allowInsideCode || (t.shift(), i.shift());
            n.isGroupInventoryEnabled && n.currentApply.status !== o.ProcurementApplyStatus.Completed || (t = _.without(t, "库存数"), i.splice(-1, 1));
            u = _.map(t, function(n) { return { value: n } });
            r = [{ cells: [{ value: "采购申请单" }, { value: n.currentApply.orderNo }] }, { cells: [{ value: "申请日期：" }, { value: n.currentApply.applyDate }] }, { cells: [{ value: "申请机构：" }, { value: n.currentApply.officeName }] }, { cells: [{ value: "申请人：" }, { value: n.currentApply.applicantName }] }, { cells: [] }, { cells: u }];
            _.each(n.currentApply.items, function(t) { var i = [];
                n.productCodeOptions.allowInsideCode && i.push({ value: t.code });
                i = i.concat([{ value: t.name }, { value: t.producer }, { value: t.specification }, { value: t.unit }]);
                n.isGroupInventoryEnabled && n.currentApply.status !== o.ProcurementApplyStatus.Completed && i.push({ value: t.curOfficeInventoryCount });
                i = i.concat([{ value: t.count }, { value: t.handledCount }, { value: t.handledCount >= t.count ? 0 : t.count - t.handledCount }]);
                r.push({ cells: i }) });
            f = { sheets: [{ title: "采购申请单" + n.currentApply.orderNo, columns: i, rows: r }] };
            e = new kendo.ooxml.Workbook(f);
            kendo.saveAs({ dataURI: e.toDataURL(), fileName: "采购申请单" + n.currentApply.orderNo + ".xlsx" }) };
    (function() { n.initBasicData = g;
        n.search = a;
        n.markAsCompleted = w;
        n.isGroupInventoryEnabled = h.isGroupInventoryEnabled();
        n.exportExcel = nt })() }]);
supplychainModule.controller("IventoryMgmtHomeCtrl", ["$log", "$scope", "$rootScope", "$modal", "$timeout", "$q", "eventAggregator", "moduleOptionProvider", "appNav", "reportSvc", "permissionProvider", "aresSlidePanel", "dataDicSvc", "tenantSvc", "officeOptionSvc", "tenantOptionSvc", "aresModalShelf", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) { "use strict"; var b = function(n) { s.goToState(n) },
        d = function() { f.all([a.warehouseDic.loadActive(), y.getOfficeOptions([y.optionKeys.DefaultInOrderAction, y.optionKeys.DefaultOutOrderAction]), v.GetTenantIsCustomizeOpen()]).then(function(n) { var u = n[0],
                    s = n[1],
                    l = n[2],
                    f, e, h, o, r;
                t.commands = [];
                s[0] && c.isAllowed("inventoryOperation.stockInBrowser") && (r = new Ares.TabCommand('<i class="iconfont icon-ruku1"><\/i>新建入库', ft, "lc-btn lc-btn-orange lc-btn-icon"), r.sensorsConfig = { sensorsEnabled: "true", sensorsEventName: "InventoryMgmtHome", sensorsEventType: "新建入库" }, t.commands.push(r));
                s[1] && c.isAllowed("inventoryOperation.stockOutBrowser") && (r = new Ares.TabCommand('<i class="iconfont icon-chuku1"><\/i>新建出库', et, "lc-btn lc-btn-primary lc-btn-icon"), r.sensorsConfig = { sensorsEnabled: "true", sensorsEventName: "InventoryMgmtHome", sensorsEventType: "新建出库" }, t.commands.push(r));
                u && u.length > 0 && (f = 0, e = u.length == 1, e && (f = u[0].id), u = _.sortBy(u, function(n) { return !n.isDefault }), u.splice(0, 0, { id: 0, name: "所有仓库" }), h = { defaultValue: f, textField: "name", valueField: "id", dataSource: u }, t.commands.push(new Ares.TabCommand("", ut, "lc-btn lc-btn-primary lc-btn-command-primary", 1, h)), o = { sensorsEnabled: "true", sensorsEventName: "InventoryMgmtHome", sensorsEventType: "新建调拨" }, e ? (i.currentWarehouseId = f, t.isAcrossOfficeInventoryTransferEnabled && c.isAllowed("inventoryOperation.stockTransferBrowser") && (r = new Ares.TabCommand('<i class="iconfont icon-zhuanhuan"><\/i>新建调拨', g, "lc-btn lc-btn-info lc-btn-icon"), r.sensorsConfig = o, window.Ares3 && (r.option = { inFold: !0 }), t.commands.push(r))) : (i.currentWarehouseId || (i.currentWarehouseId = f), c.isAllowed("inventoryOperation.stockTransferBrowser") && (r = new Ares.TabCommand('<i class="iconfont icon-zhuanhuan"><\/i>新建调拨', g, "lc-btn lc-btn-info lc-btn-icon"), r.sensorsConfig = o, window.Ares3 && (r.option = { inFold: !0 }), t.commands.push(r))));
                c.isAllowed("inventoryOperation.stockCheck") && (r = new Ares.TabCommand('<i class="iconfont icon-kucunpandian"><\/i>新建盘点', ot, "lc-btn lc-btn-info lc-btn-icon"), r.sensorsConfig = { sensorsEnabled: "true", sensorsEventName: "InventoryMgmtHome", sensorsEventType: "新建盘点" }, window.Ares3 && (r.option = { inFold: !0 }), t.commands.push(r));
                l.data || (r = new Ares.TabCommand('<i class="iconfont icon-wenhao"><\/i>帮助', at, "lc-btn lc-btn-cyan lc-btn-icon lc-btn-icon-narrow"), window.Ares3 && (r.option = { afterFold: !0 }), t.commands.push(r));
                k() }) },
        nt = function() { var i, r, n;
            t.states = [new Ares.TabItem("supplychain.inventory.inorder", "入库管理", null, "inventoryOperation.stockInBrowser", null, null, null), new Ares.TabItem("supplychain.inventory.outorder", "出库管理", null, "inventoryOperation.stockOutBrowser", null, null, null), new Ares.TabItem("supplychain.inventory.transfer", "调拨管理", null, "inventoryOperation.stockTransferBrowser", null, null, null), new Ares.TabItem("supplychain.inventory.check", "盘点管理", null, "inventoryOperation.stockCheck", null, null, null), ];
            window.Ares3 ? (n = ["supplychain.inventory.manage.currently"], i = new Ares.TabItem("supplychain.inventory.manage", "库存管理", null, "inventoryBrowse.stockStatus", n, null, null), i.sensorsConfig = { sensorsEnabled: "true", sensorsEventName: "InventoryMgmtHome", sensorsEventType: "库存管理(3.0)" }, t.states.unshift(i), r = new Ares.TabItem("supplychain.inventory.flow", "库存流水", null, "inventoryBrowse.stockCountSummary", null, null, null), r.sensorsConfig = { sensorsEnabled: "true", sensorsEventName: "InventoryMgmtHome", sensorsEventType: "库存流水(3.0)" }, t.states.push(r)) : (n = ["supplychain.inventory.manage.currently", "supplychain.inventory.manage.flow", "supplychain.inventory.manage.warehouse", "supplychain.inventory.manage.traceability"], t.states.unshift(new Ares.TabItem("supplychain.inventory.manage", "库存管理", null, "inventoryBrowse.stockStatus", n, null, null))) },
        tt = function(n) { var i, r, u, f;
            n = n || {};
            i = _.find(t.states, { name: "supplychain.inventory.inorder" });
            i && (i.hint = n.actionRecord ? n.actionRecord.inOrderHint : 0);
            r = _.find(t.states, { name: "supplychain.inventory.outorder" });
            r && (r.hint = n.actionRecord ? n.actionRecord.outOrderHint : 0);
            u = _.find(t.states, { name: "supplychain.inventory.transfer" });
            u && (u.hint = n.actionRecord ? n.actionRecord.transferOrderHint : 0);
            f = _.find(t.states, { name: "supplychain.inventory.check" });
            f && (f.hint = n.actionRecord ? n.actionRecord.checkOrderHint : 0) },
        it = function() { p.getTenantOption("IsAcrossOfficeInventoryTransferEnabled").then(function(n) { t.isAcrossOfficeInventoryTransferEnabled = n;
                d();
                nt() }) },
        k = function() { h.getInventoryHintSummary(0).success(function(n) { tt(n) }).error(function(t) { n.log("IventoryMgmtHomeCtrl:" + t) }) },
        rt = function() { e.subscribe(t, e.events.RefreshIventoryHint, function() { k() });
            e.subscribe(t, e.events.WarehouseEdited, function() { d() }) },
        ut = function(n) { i.currentWarehouseId = n.sender.value() * 1;
            k();
            e.publish(e.events.GlobalWarehouseChanged, i.currentWarehouseId, "IventoryMgmtHomeCtrl") },
        ft = function() { ht().then(function(n) { n && (i.currentState == "supplychain.inventory.inorder" ? e.publish(e.events.IventoryInOrderCreated, n, "IventoryMgmtHomeCtrl") : (b("supplychain.inventory.inorder"), u(function() { e.publish(e.events.IventoryActionMenuChanged, n, "IventoryMgmtHomeCtrl") }, 500))) }) },
        et = function() { y.getOfficeOption(y.optionKeys.IsTakeOutWorkflowEnabled).then(function(n) { ct(n).then(function(n) { n && (i.currentState == "supplychain.inventory.outorder" ? e.publish(e.events.IventoryOutOrderCreated, n, "IventoryMgmtHomeCtrl") : (b("supplychain.inventory.outorder"), u(function() { e.publish(e.events.IventoryActionMenuChanged, n, "IventoryMgmtHomeCtrl") }, 500))) }) }) },
        ot = function() { lt().then(function(n) { n && (i.currentState == "supplychain.inventory.check" ? e.publish(e.events.IventoryCheckOrderCreated, n, "IventoryMgmtHomeCtrl") : (b("supplychain.inventory.check"), u(function() { e.publish(e.events.IventoryActionMenuChanged, n, "IventoryMgmtHomeCtrl") }, 500))) }) },
        g = function() { st().then(function(n) { n && (i.currentState == "supplychain.inventory.transfer" ? e.publish(e.events.IventoryTransferOrderCreated, n, "IventoryMgmtHomeCtrl") : (b("supplychain.inventory.transfer"), u(function() { e.publish(e.events.IventoryActionMenuChanged, n, "IventoryMgmtHomeCtrl") }, 500))) }) },
        st = function() { var n = w.open({ title: "新建调拨", titleIconClass: "iconfont icon-zhuanhuan", template: "<inventory-transfer-order-edit-modal-view><\/inventory-transfer-order-edit-modal-view>", controller: "InventoryTransferOrderEditModalCtrl", resolve: { host: function() { return { supplier: null } } }, confirmClose: !0 }); return n.result },
        ht = function() { var n = w.open({ title: "新建入库单", titleIconClass: "iconfont icon-ruku1", template: "<inventory-in-order-edit-modal-view><\/inventory-in-order-edit-modal-view>", controller: "InventoryInOrderEditModalCtrl", confirmClose: !0, resolve: { host: function() { return {} } } }); return n.result },
        ct = function() { var n = w.open({ title: "新建出库单", titleIconClass: "iconfont icon-chuku1", template: "<inventory-out-order-edit-modal-view><\/inventory-out-order-edit-modal-view>", controller: "InventoryOutOrderEditModalCtrl", confirmClose: !0, resolve: { host: function() { return {} } } }); return n.result },
        lt = function() { var n = w.open({ title: "新增盘点单", titleIconClass: "iconfont icon-kucunpandian", template: "<inventory-check-order-edit-modal-view><\/inventory-check-order-edit-modal-view>", controller: "InventoryCheckOrderEditModalCtrl", confirmClose: !0, resolve: { host: function() { return { warehouse: {} } } } }); return n.result },
        at = function() { e.publish(e.events.HelpSlideToggled, {}, "InventoryMgmtHomeCtrl") };
    (function() { rt();
        it() })() }]);
var criticalProductTraceability;
(function() { var n = function() {
        function n(n, t, i, r) { this.$scope = n;
            this.$q = t;
            this.inventorySvc = i;
            this.$filter = r } return n.prototype.searchCriticalProduct = function() { var t = this.$q.defer(),
                n = this; return n.inventorySvc.searchCriticalProductTraceability(n.$scope.unicode).then(function(i) { n.$scope.isShow = !0;
                i.data ? (n.$scope.criticalProductTraceabilityDto = i.data, n.$scope.criticalProductTraceabilityDto.details && _.each(n.$scope.criticalProductTraceabilityDto.details, function(t) { switch (t.detailType) {
                        case "Procurement":
                            t.detailTitle = "制作采购单";
                            t.personTitle = "制单人"; break;
                        case "ProcurementCheck":
                            t.detailTitle = "采购单审核";
                            t.personTitle = "审核人"; break;
                        case "InventoryInOrder":
                            t.detailTitle = n.$filter("toInOrderActionString")(t.orderAction);
                            t.personTitle = "入库人"; break;
                        case "UnicodePrint":
                            t.detailTitle = "唯一码加工";
                            t.personTitle = "打印人"; break;
                        case "InventoryOutOrder":
                            t.detailTitle = n.$filter("toOutOrderActionString")(t.orderAction);
                            t.personTitle = "出库人"; break;
                        case "SaleOrder":
                            t.detailTitle = "销售开单";
                            t.personTitle = "制单人"; break;
                        case "TakeOrder":
                            t.detailTitle = "领用开单";
                            t.personTitle = "制单人"; break;
                        case "ChargeOrder":
                            t.detailTitle = "耗材收费";
                            t.personTitle = "收费人"; break;
                        case "ProductUse":
                            t.detailTitle = "耗材使用";
                            t.personTitle = "使用人" } })) : n.$scope.criticalProductTraceabilityDto = null;
                t.resolve() }), t.promise }, n.$inject = ["$scope", "$q", "inventorySvc", "$filter"], n }();
    systemToolModule.controller("CriticalProductTraceabilityCtrl", Ares.tsController(n)) })(criticalProductTraceability || (criticalProductTraceability = {}));
supplychainModule.controller("InventoryCurrentlyListCtrl", ["$log", "$scope", "$rootScope", "$modal", "eventAggregator", "productSvc", "aresDialog", "dataDicSvc", "organizationSvc", "inventoryProductSvc", "officeOptionSvc", "warehouseSvc", "loginContext", "aresNotification", "aresTreeViewUtil", "inventoryUtil", "$q", "$timeout", "productUnitySvc", "moduleOptionProvider", "warehouseUtil", "enums", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt) { "use strict"; var tt = function(n) { var r = { pageIndex: n || 1, pageSize: t.searchCriteria.pageSize, productIds: [], categoriesIds: t.selCategoriesIds, batchNumber: t.searchCriteria.batchNumber, expiredDate: t.searchCriteria.expiredDate ? moment(t.searchCriteria.expiredDate).format("YYYY-MM-DD") : "", unicode: t.searchCriteria.unicode, isOnlyShowCritical: t.searchCriteria.isOnlyShowCritical, includeZeroCount: t.searchCriteria.includeZeroCount, dealerId: t.searchCriteria.dealerId, sortField: t.searchCriteria.sortField, sortDirection: t.searchCriteria.sortDirection }; return t.searchSelectedProduct && (r.productIds = t.searchSelectedProduct.products ? _.pluck(t.searchSelectedProduct.products, "id") : [t.searchSelectedProduct.id]), r.warehouseId = i.currentWarehouseId != 0 ? i.currentWarehouseId : null, r },
        it = function(n) { var i = tt(n),
                r; return t.warningType > 0 && (i.isOnlyShowCountWarn = !0, t.warningType == 2 && (i.isOnlyShowExpiratingWarn = !0)), r = w.defer(), h.searchInventoryProduct(i).success(function(n) { if (n) { t.totalResult = n.totalResult;
                    t.searchCriteria.pageIndex = n.page.pageIndex;
                    t.currentInventoryList = n.page;
                    et(t.currentInventoryList); var i = rt(t.currentInventoryList.items);
                    st(i) } b(function() { t.initTableView() });
                r.resolve() }), r.promise },
        et = function(n) { ot().then(function() { _.each(n.items, function(n) { var i = _.find(t.baseData.warehouses, function(t) { return t.id === n.warehouseId });
                    n.isConsignee = i && i.grade === nt.WarehouseGrade.Consignee.value;
                    t.warningType == 2 && t.expiratingProducts && (n.batches = _.filter(n.batches, function(n) { return n.expiredDate != null }));
                    _.each(n.batches, function(i) { var u, r, f, e;
                        i.expiredDate && t.expiratingProducts && (u = moment(i.expiredDate).format("YYYY-MM-DD"), r = _.find(t.expiratingProducts, function(t) { return t.productId == i.productId && t.warehouseId == n.warehouseId && moment(t.expiredDate).format("YYYY-MM-DD") == u }), r ? (f = r.expiredDayOffset >= 0 ? "离到期时间：" : "已过期：", e = r.expiredDayOffset >= 0 ? r.expiredDayOffset : r.expiredDayOffset * -1, i.expiredTooltip = f + e + "天") : t.warningType == 2 && (i.isDelete = !0)) });
                    n.batches = _.filter(n.batches, function(n) { return !n.isDelete });
                    n.isUnicodeVisible = n.batches.some(function(n) { return n.unicode }) }) }) },
        ot = function() { var n = w.defer(); return o.productCategoryDic.load().then(function(i) { t.categories = i;
                n.resolve() }), n.promise },
        st = function(n) { k.getProductPackageByProductIds(n).success(function(n) { t.productPackages = n;
                _.each(t.currentInventoryList.items, function(t) { var r = _.find(n, function(n) { return n.fromProductId === t.productId }),
                        i;
                    r && (t.unpackProductExists = !0);
                    i = _.find(n, function(n) { return n.toProductId === t.productId });
                    i && (t.packProductExists = !0) }) }) },
        ht = function() { p.getProductCategories().then(function(n) { t.selCategoryId = 0;
                t.selCategory = { name: "全部分类", id: 0 };
                t.categoriesTree = y.unflatten(n, "showOrder");
                t.categoriesTree.splice(0, 0, t.selCategory) }) },
        ut = function() { var n = w.defer(),
                i = tt(); return h.getInventoryProductCountWarn(i.warehouseId).success(function(i) { t.procurementPlanProductIds = rt(i);
                t.procurementPlanNumber = i.length;
                n.resolve() }), n.promise },
        ft = function() { var n = w.defer(); return c.getOfficeOption(c.optionKeys.IsInventoryValidityWarnEnabled).then(function(i) { if (t.isInventoryValidityWarnEnabled = i, i) { var r = tt();
                    h.getInventorytProductExpiratingWarnList(r.warehouseId).success(function(i) { t.expiratingProducts = i;
                        t.expiratingProductIds = rt(i);
                        t.expiratingNumber = i.length;
                        n.resolve() }) } else n.resolve() }), n.promise },
        rt = function(n) { var t = _.pluck(n, "productId"); return _.uniq(t) },
        ct = function() { u.subscribe(t, u.events.GlobalWarehouseChanged, function() { ft().then(function() { ut().then(function() { t.warningType == 1 ? t.searchCriteria.productIds = t.procurementPlanProductIds : t.warningType == 2 && (t.searchCriteria.productIds = t.expiratingProductIds);
                        it().then(function() { t.warningType > 0 && (t.isExpandAll = !1, t.expandAllChange(t.currentInventoryList)) }) }) }) }) },
        lt = function() { var n = []; return t.baseData = {}, n.push(o.warehouseDic.loadActive().then(function(n) { var i = g.filterWarehouses(n);
                i = _.sortBy(i, function(n) { return !n.isDefault });
                t.baseData.warehouses = i })), t.isConsignmentModeEnabled && n.push(l.getDealerWarehouseList().then(function(n) { n && n.data && (t.baseData.dealerWarehouses = angular.copy(n.data), t.baseData.dealerWarehouses.splice(0, 0, { dealerId: 0, dealerName: "所属寄售供应商" })) })), w.all(n) },
        at = function() { p.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        vt = function() { var n = w.defer(); return c.getOfficeOptions([c.optionKeys.IsProductUnicodeManagementEnabled, c.optionKeys.IsConsignmentModeEnabled]).then(function(i) { _.isArray(i) ? (t.isProductUnicodeManagementEnabled = i[0], t.isConsignmentModeEnabled = i[1]) : (t.isProductUnicodeManagementEnabled = !1, t.isConsignmentModeEnabled = !1);
                n.resolve(!0) }), n.promise };
    (function() { t.isInventoryCostVisible = a.isInventoryCostAllowed;
        t.search = it;
        t.initSearchCriteria = tt;
        t.searchCriteria = { pageIndex: 1, pageSize: 20, productId: "", productIds: [], batchNumber: "", unicode: "", expiredDate: null, isOnlyShowCritical: !1, includeZeroCount: !1, dealerId: 0, sortField: null, sortDirection: null };
        ft().then(function() { ht();
            ut();
            vt().then(function() { lt().then(function() { it() }) }) });
        ct();
        at() })() }]);
supplychainModule.controller("InventoryOutOrderCountDialogCtrl", ["$q", "$log", "$scope", "$modalInstance", "host", "loginContext", "aresNotification", "procurementSvc", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s) { "use strict"; var c = function() { r.close(!1) },
        l = function(n) { if (n.outCount > n.count && !i.isAllowExceedInventoryCount && (n.outCount = n.count), n.outCount === n.count) n.amount = n.batchTotalAmount;
            else { var t = Ares.priceToFixed(n.outCount * n.price);
                n.amount = i.isAllowExceedInventoryCount ? t : _.min([t, n.batchTotalAmount]) } h() },
        h = function() { var n = 0,
                t = 0;
            angular.forEach(i.orderItem.batches, function(i) { n += i.outCount * 1 || 0;
                t += i.amount * 1 || 0 });
            i.orderItem.outCount = n;
            i.orderItem.amount = t;
            i.orderItem.price = Ares.priceToFixed(t / n) },
        a = function() { var n; return !i.isAllowExceedInventoryCount && (n = _.find(i.orderItem.batches, function(n) { return n.outCount > n.count }), n) ? "物品【" + i.orderItem.product.name + "】库存数不足！" : "" },
        v = function() { if (!i.isOnlyShow) { h(); var n = a(); if (n) { s.warn({ message: n }); return } } r.close(i.orderItem) };
    (function() { i.close = c;
        i.save = v;
        i.onCountChanged = l;
        i.orderItem = u.orderItem;
        i.isOnlyShow = u.isOnlyShow;
        i.isInventoryCostVisible = u.isInventoryCostVisible;
        i.isExpireDateVisible = u.orderItem.batches.some(function(n) { return n.expiredDate });
        i.isBatchNumberVisible = u.orderItem.batches.some(function(n) { return n.batchNumber });
        i.isUnicodeVisible = u.orderItem.batches.some(function(n) { return n.unicode });
        i.isAllowExceedInventoryCount = u.isAllowExceedInventoryCount })() }]);
supplychainModule.controller("InventoryProductWarehouseDetailViewCtrl", ["$log", "$scope", "$rootScope", "$filter", "eventAggregator", "$modal", "productSvc", "aresDialog", "dataDicSvc", "organizationSvc", "inventorySvc", "gridOptionUtil", "systemitemSvc", "aresNotification", "formatUtil", "userOptionSvc", "$q", "reportUtil", "inventoryUtil", "reportSvc", "officeOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g) { "use strict"; var rt = [{ id: null, name: "是否为高值耗材" }, { id: !0, name: "是" }, { id: !1, name: "否" }],
        ut = function() { var n = w.defer(); return nt(!0).then(function() { n.resolve(t.inventoryProductSummaryList) }), n.promise },
        ft = function() { var n = w.defer(); return nt().then(function() { n.resolve(t.inventoryProductList) }), n.promise },
        et = function() { var n = w.defer(); return l.loadColumnsOption(l.keys.inventoryOrderItemSummaryGridOption).then(function(i) { t.showSummaryColumns = i;
                n.resolve(!0) }), n.promise },
        tt = function() { var n = w.defer(); return l.loadColumnsOption(l.keys.inventoryOrderItemGridOption).then(function(i) { t.showColumns = i;
                n.resolve(!0) }), n.promise },
        ot = function() { var n = w.defer(); return g.getOfficeOptions([g.optionKeys.IsProductUnicodeManagementEnabled, g.optionKeys.IsConsignmentModeEnabled]).then(function(i) { _.isArray(i) ? (t.isProductUnicodeManagementEnabled = i[0], t.isConsignmentModeEnabled = i[1]) : (t.isProductUnicodeManagementEnabled = !1, t.isConsignmentModeEnabled = !1);
                n.resolve(!0) }), n.promise },
        nt = function(n) { var r = w.defer(),
                i; return t.searchCriteria.pageSize = t.pageSize, t.searchCriteria.pageIndex = t.pageIndex, t.searchCriteria.sortField = t.sortField, t.searchCriteria.sortDirection = t.sortDirection, i = angular.copy(t.searchCriteria), t.setSearchCriteria(i), n ? c.searchInventoryOrderItemSummary(i).success(function(i) { t.totalResult = i.sumInfo; var u = it(i, n);
                t.inventoryProductSummaryList = u;
                r.resolve(!0) }) : c.searchInventoryOrderItem(i).success(function(i) { t.totalResult = i.sumInfo; var u = it(i, n);
                t.inventoryProductList = u;
                r.resolve(!0) }), r.promise },
        it = function(n, t) { var i = {}; return angular.forEach(n.items, function(n) { var i = moment(n.orderDate).format("YYYY-MM-DD");
                i < "2017-12-21" && (n.afterAmount = "---", n.afterCount = "---", n.afterPrice = "---");
                n.orderDate = r("toDateString")(n.orderDate);
                n.recordCreatedTime = r("toDateString")(n.recordCreatedTime);
                n.expiredDate && (n.expiredDate = r("toDateString")(n.expiredDate));
                t || n.batchCount < 0 && n.batchAmount > 0 && (n.batchAmount = -1 * n.batchAmount) }), i.pageIndex = n.pageIndex, i.pageSize = n.pageSize, i.pageCount = n.pageCount, i.totalCount = n.totalCount, i.itemList = n.items || [], i },
        st = function() { u.subscribe(t, u.events.IventoryInOrderCreated, function() { t.refreshGrid() });
            u.subscribe(t, u.events.GlobalWarehouseChanged, function() { t.refreshGrid() }) },
        ht = function() { var n = b.getDefaultTimeSpan().startTime,
                i = b.getDefaultTimeSpan().endTime;
            t.searchTimeRange = { startDate: n, endDate: i };
            t.searchCriteria = { startDate: n, endDate: i, action: "all", consigneeType: "all", isCritical: null, unicode: null, consignmentDealerId: 0 } },
        ct = function() { return k.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        lt = function() { var n = angular.copy(t.searchCriteria);
            t.setSearchCriteria(n);
            d.createInventoryOrderItemBackgroundReport(n).success(function(n) { var t = n.isSucceed ? n.hasTaskCancelled ? "后台报表'" + n.newTask.reportName + "'已创建！（已取消10分钟内同类报表）" : "后台报表'" + n.newTask.reportName + "'已创建！" : "已存在处理的同类型的报表（10分钟内只能创建一个同类型报表）！";
                o.info("信息", t) }) };
    (function() { t.initSearchData = ht;
        t.pageIndex = 1;
        t.pageSize = 15;
        t.maxPageCount = 15;
        t.onPageChanged = ft;
        t.query = nt;
        t.loadColumnsOption = tt;
        t.loadColumnsOptionSummary = et;
        t.onPageChangedSummary = ut;
        t.initProductCodeOptions = ct;
        t.createInventoryOrderItemBackgroundReport = lt;
        t.isCriticalDropdownData = rt;
        tt();
        t.loadProductUnicodeManagementEnabled = ot;
        st() })() }]);
supplychainModule.controller("InventoryProcurementApplyListCtrl", ["$log", "$scope", "$timeout", "aresDialog", "loginContext", "permissionProvider", "aresNotification", "$q", "enums", "reportUtil", "inventoryUtil", "practiceSvc", "procurementApplyOrderSvc", "$filter", "dataDicSvc", "$sce", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p) { "use strict"; var k = function() { var n = []; return w(), n.push(y.currentOfficeWorkProviderDic.load().then(function(n) { n.splice(0, 0, { id: 0, name: "申请员工" });
                t.providers = n })), n.push(y.workflowDefinitionDic.load().then(function(n) { t.procurementApplyWorkflow = _.find(n, function(n) { return n.workflowType == s.WorkflowType.ProcurementApply && !n.isDisabled == !0 }) })), o.all(n) },
        d = function() { var n = h.getDefaultTimeSpan();
            t.searchTimeRange = { startDate: moment(n.startTime).format("YYYY-MM-DD"), endDate: moment(n.endTime).format("YYYY-MM-DD") } },
        g = function() { t.searchCriteria.startDate = t.searchTimeRange.startDate;
            t.searchCriteria.endDate = t.searchTimeRange.endDate;
            t.onSearchProcurementApply() },
        w = function() { t.searchCriteria = { startDate: t.searchTimeRange.startDate, endDate: t.searchTimeRange.endDate, status: "", applicantId: 0, OrderNo: "", productIds: null, pageIndex: 1, pageSize: 10 } },
        nt = function() { var i = o.defer(),
                n = angular.copy(t.searchCriteria); return n.endDate && (n.endDate = moment(n.endDate).add(1, "days").format("YYYY-MM-DD")), a.search(n).success(function(n) { n ? (t.procurementApplyList = _.map(n.items, function(n) { if (n.status === s.ProcurementApplyStatus.Rejected) { var t = '<label class="label label-danger" data-toggle="tooltip" data-placement="bottom" style="cursor: pointer;" title="审批不通过原因：' + n.workflowRejectedNotes + '" data-viewport=".procurement-apply-list-item">已拒绝 <i class="iconfont icon-xinxi" style="font-size: 12px;"><\/i><\/label>';
                        n.statusHtml = p.trustAsHtml(t) } else n.statusHtml = ht(n.status); return n.applyTimeStr = v("toDateString")(n.applyTime), n.isCanReApply = tt(n), n.isCanSubmitWorkflow = b(n, !0), n.isCanSubmitOrder = b(n, !1), n }), t.procurementApplyTotalCount = n.totalCount) : (t.procurementApplyList = [], t.procurementApplyTotalCount = 0);
                t.refreshTooltips();
                i.resolve() }), i.promise },
        tt = function(n) { return n.status === s.ProcurementApplyStatus.Rejected || n.status === s.ProcurementApplyStatus.Cancelled },
        b = function(n, i) { return n.status != s.ProcurementApplyStatus.Pending ? !1 : i ? t.procurementApplyWorkflow : !t.procurementApplyWorkflow },
        lt = function(n) { return angular.forEach(n, function(n) { var r = _.find(t.offices, function(t) { return t.id == n.officeId }),
                    i;
                n.officeName = r.abbreviation;
                n.orderDateStr = moment(n.orderDate).format("YYYY-MM-DD HH:mm:ss");
                n.isEdit = !1;
                n.isLinkedCare = n.type == s.ProcurementOrderType.LinkedCare;
                n.items = [];
                angular.forEach(n.procurementOrders, function(t) { angular.forEach(t.procurementOrderItems, function(t) { t.hasReturnOrder = t.returnCountInstorage + t.returnCountPreInstorage > 0;
                        n.items.push(t) }) });
                n.isLinkedCare && (i = _.find(n.items, function(n) { return n.waybillId > 0 }), n.hasWayBill = i ? !0 : !1);
                n.hasReturnOrder = _.some(n.items, function(n) { return n.returnCountInstorage + n.returnCountPreInstorage > 0 }) }), n },
        it = function(n) { n && (n.currentClass = Ares.isInteger(n.number) && n.number > 0 ? "" : "error-input", n.currentPriceClass = Ares.isValidNumber(n.price) && n.price > 0 ? "" : "error-input") },
        rt = function(n) { n && (n.currentCouponAmountClass = Ares.isValidNumber(n.couponAmount) ? "" : "error-input", n.currentFreigthClass = Ares.isValidNumber(n.freight) ? "" : "error-input") },
        ut = function() { c.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        ft = function(n) { a.updateStatus(n, s.ProcurementApplyStatus.WaitHandle).success(function() { e.success("提交成功");
                t.onSearchProcurementApply() }) },
        et = function(n) { var t = o.defer(); return a.startWorkflowProcurementApply(n).success(function() { e.success("审批提交成功");
                t.resolve() }), t.promise },
        ot = function(n) { a.cancelById(n).success(function() { e.success("作废成功");
                t.onSearchProcurementApply() }) },
        st = function(n) { var t = o.defer(); return a.getById(n).then(function(n) { t.resolve(n.data) }, function() { e.error("无法获取采购申请详情") }), t.promise },
        ht = function(n) { var t = ""; switch (n) {
                case 0:
                    t = '<div class="label label-warning">待提交<\/div>'; break;
                case 1:
                    t = '<div class="label label-warning">待处理<\/div>'; break;
                case 2:
                    t = '<div class="label label-success">已处理<\/div>'; break;
                case 3:
                    t = '<div class="label label-warning">部分处理<\/div>'; break;
                case 4:
                    t = '<div class="label label-default">已作废<\/div>'; break;
                case 5:
                    t = '<div class="label label-warning">待审批<\/div>'; break;
                case 6:
                    t = '<div class="label label-default">已拒绝<\/div>'; break;
                default:
                    t = '<div class="label label-default">未知<\/div>' } return p.trustAsHtml(t) },
        ct = function() { var n = angular.copy(t.searchCriteria),
                i; return n.endDate && (n.endDate = moment(n.endDate).add(1, "days").format("YYYY-MM-DD")), n.totalItemCount = t.procurementApplyTotalCount, i = o.defer(), a.invokeApplyOrderListToZip(n).success(function(n) { var t = n.isSucceed ? n.hasTaskCancelled ? "后台报表'" + n.newTask.reportName + "'已创建！（已取消10分钟内同类报表）" : "后台报表'" + n.newTask.reportName + "'已创建！" : "已存在处理的同类型的报表（10分钟内只能创建一个同类型报表）！";
                i.resolve(t) }).error(function(n) { i.reject(n) }), i.promise };
    (function() { t.isInPayOrderAllowed = f.isAllowed("procurement.procurementInPayOrder");
        t.searchProcurementApply = nt;
        t.initSearchData = w;
        t.initDefaultData = k;
        t.cancelProcurementApply = ot;
        t.formatNumber = it;
        t.formatPayOrderNumber = rt;
        t.submitProcurementApply = ft;
        t.submitWorkflowProcurementApply = et;
        t.getApplyDetail = st;
        t.onSearchTimeRangeChanged = g;
        t.invokeApplyOrderListToZip = ct;
        d();
        ut() })() }]);
supplychainModule.controller("InventoryProcurementReturnOrderListCtrl", ["$log", "$scope", "$filter", "aresConfirmDialog", "loginContext", "procurementSvc", "aresNotification", "$q", "dataDicSvc", "enums", "$timeout", "inventoryUtil", "$sce", "officeSelectorUtil", "officeSvc", "excelExportUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p) { "use strict"; var ut = i("toFormatPrice"),
        k = function() { s.workflowDefinitionDic.load().then(function() { return w() }).then(function() { c(function() { t.initTableView() }) }) },
        w = function() { var i = o.defer(),
                n = angular.copy(t.searchCriteria); return n.startDate = moment(n.startDate).format("YYYY-MM-DD"), n.endDate = moment(n.endDate).add(1, "days").format("YYYY-MM-DD"), n.officeIds = t.isGroup ? t.selectedOfficeIdsArray : [u.officeId], n.orderNo = t.searchCriteria.orderNo, n.supplier = t.currentSupplier == "供应商" ? "" : t.currentSupplier, f.searchProcurementReturnOrder(n).then(function(n) { n.data && (t.procuementReturnOrderList = d(n.data.page.items), t.procuementReturnOrderTotalCount = n.data.page.totalCount, t.totalResult = n.data.totalResult, c(function() { t.initTableView() }));
                i.resolve(!0) }), i.promise },
        d = function(n) { return angular.forEach(n, function(n) { var i = _.find(t.offices, function(t) { return t.id == n.officeId });
                n.officeName = i.abbreviation;
                n.stateLastUpdated = moment(n.stateLastUpdated).format("YYYY-MM-DD HH:mm");
                n.recordCreatedTime = moment(n.recordCreatedTime).format("YYYY-MM-DD");
                n.isCanOutOrder = n.officeId == u.officeId && !n.isOnlyServiceOrder && (n.status == 0 || n.status == 4);
                n.isShow = n.returnApplyOrder === null || n.returnApplyOrder != null && (n.returnApplyOrder.status === 3 || n.returnApplyOrder.status === 4 && n.status === 1 && n.type === 3 || n.returnApplyOrder.status === 4 && n.status === 3) }), g(n), n },
        g = function(n) { _.each(n, function(n) { var t = "",
                    i = ""; if (n.returnApplyOrder) { switch (n.returnApplyOrder.status) {
                        case 0:
                            t = '<span class="label label-warning">申请中<\/span>'; break;
                        case 1:
                            t = '<span class="label label-warning">申请已通过<\/span>'; break;
                        case 2:
                            t = '<span class="label label-danger">已拒绝<\/span>'; break;
                        case 3:
                            t = '<span class="label label-success">已退款<\/span>'; break;
                        case 4:
                            t = n.status === 1 ? n.type === 3 ? '<span class="label label-success">已退款<\/span>' : '<span class="label label-warning">待商城确认<\/span>' : n.status === 4 ? '<span class="label label-warning">部分出库<\/span>' : n.status === 3 ? '<span class="label label-success">已退款<\/span>' : '<span class="label label-warning">待出库<\/span>'; break;
                        default:
                            t = '<span class="label label-warning">未知<\/span>' } switch (n.returnApplyOrder.applyType) {
                        case 0:
                            i = '<span class="lc-label ">已发货物品退货<\/span>'; break;
                        case 1:
                            i = '<span class="lc-label ">未发货物品退款<\/span>'; break;
                        default:
                            i = '<span class="lc-label ">未知<\/span>' } } else { switch (n.status) {
                        case 0:
                            t = '<span class="label label-warning">待出库<\/span>'; break;
                        case 1:
                            t = '<span class="label label-success">已处理<\/span>'; break;
                        case 2:
                            t = '<span class="label label-default">已作废<\/span>'; break;
                        case 3:
                            t = '<span class="label label-success">已退款<\/span>'; break;
                        case 4:
                            t = '<span class="label label-warning">部分出库<\/span>'; break;
                        default:
                            t = '<span class="label label-warning">未知<\/span>' } switch (n.type) {
                        case 1:
                            i = '<span class="lc-label ">未入库物品退货<\/span>'; break;
                        case 2:
                            i = '<span class="lc-label ">已入库物品退货<\/span>'; break;
                        case 3:
                            i = '<span class="lc-label ">未发货物品退款<\/span>'; break;
                        default:
                            i = '<span class="lc-label ">未知<\/span>' } } n.statusLabel = a.trustAsHtml(t);
                n.typeLabel = a.trustAsHtml(i) }) },
        b = function() { var n = new Date,
                i = moment(n).startOf("day").date(1).toDate();
            t.searchCriteria = { startDate: i, endDate: n, status: -100, payOrderNo: "", orderNo: "", pageIndex: 0, pageSize: 10 } },
        nt = function(n) { r.warn({ message: "确认取消该退货单？", showCancelBtn: !0 }).then(function() { f.cancelProcurementReturnOrder(n.id).success(function() { w();
                    e.success("操作成功") }).error(function(n) { e.error(n.message || "操作失败") }) }) },
        tt = function() { l.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        it = function() { var n = o.defer(),
                i = [s.officeDic.load().then(function(n) { t.offices = n })]; return t.isGroup && i.push(y.getSelfAndChildOfficesByGroupId(u.officeId, !0).success(function(n) { t.officeTreeData = v.setId(n); var i = _.values(v.flattenToMap(n));
                t.selectedOfficeIdsArray = _.pluck(i, "officeId") })), o.all(i).then(function() { n.resolve(!0) }), n.promise },
        rt = function(n) { var l = p.generateColumnSettings,
                u = p.Row,
                a = p.MainHeaderRow,
                t = p.HeaderCell,
                i = p.RegularCell,
                s = p.NumberCell,
                f = p.PriceCell,
                v = l([50, 100, 150, 80, 150, 50, 100, 100, 150]),
                r = [],
                e, o, h, c;
            r.push(new a("采购退货单", 9));
            r.push(new u([new t("退货机构：", 2, "left"), new i(n.officeName, 2), new t("供应商：", 1, "left"), new i(n.supplier, 2), new t("退货人：", 1, "left"), new i(n.recordCreatedUserName, 1)]));
            r.push(new u([new t("退货单号：", 2, "left"), new i(n.orderNo || n.returnApplyOrder.serviceOrderNo, 2), new t("单据日期：", 1, "left"), new i(n.recordCreatedTime, 2), new t("制单人：", 1, "left"), new i(n.recordCreatedUserName, 1)]));
            r.push(new u([new t("退货原因：", 2, "left"), new i(n.notes, 7)]));
            r.push(new u([new t("序号"), new t("内部编码"), new t("名称"), new t("品牌"), new t("规格"), new t("单位"), new t("退货单价"), new t("数量"), new t("金额")]));
            e = 0;
            o = 0;
            _.each(n.items, function(n, t) { r.push(new u([new i(t + 1), new i(n.code), new i(n.name), new i(n.producer), new i(n.specification), new i(n.unit), new f(n.price), new s(n.count), new f(n.amount)]));
                e += n.count;
                o += n.amount });
            r.push(new u([new t("合计", 7, "left"), new s(e), new f(o)]));
            r.push(new u([new t("退货人签字：           ", 7, "right")]));
            h = { sheets: [{ title: "采购退货单" + (n.orderNo || n.returnApplyOrder.serviceOrderNo), columns: v, rows: r }] };
            c = new kendo.ooxml.Workbook(h);
            kendo.saveAs({ dataURI: c.toDataURL(), fileName: "采购退货单" + (n.orderNo || n.returnApplyOrder.serviceOrderNo) + ".xlsx" }) };
    (function() { t.searchProcurementReturnOrder = w;
        t.initSearchData = b;
        t.deleteReturnOrder = nt;
        t.loadOffices = it;
        t.initDefaultData = k;
        t.exportExcel = rt;
        b();
        tt() })() }]);
supplychainModule.controller("InventoryProcurementReturnOrderOutItemCtrl", ["$log", "$q", "$timeout", "$scope", "$modalInstance", "host", "inventorySvc", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var h = function() { u.dismiss() },
        c = function() { var n = s();
            n != r.returnOrderItem.count ? o.error("退货数量不正确") : u.close(r.returnOrderItem) },
        s = function() { if (r.returnOrderItem.itemBatchs && r.returnOrderItem.itemBatchs.length > 0) return r.returnOrderItem.itemBatchs.map(function(n) { return parseFloat(n.returnCount) }).reduce(function(n, t) { return n + t });
            o.info("库存不足") };
    (function() { r.clean = h;
        r.save = c;
        r.returnOrderItem = f.returnOrderItem;
        r.getReturnOrderItemSumCount = s;
        r.returnOrderItem.outCount = r.getReturnOrderItemSumCount() })() }]);
supplychainModule.controller("ProcurementAssistanceListCtrl", ["$q", "$scope", "$timeout", "inventoryUtil", "dataDicSvc", "aresTreeViewUtil", "procurementSvc", "productSvc", "inventoryProductSvc", "toFormatPriceFilter", "aresNotification", "officeUtil", "officeOptionSvc", "permissionProvider", "productUnitySvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { "use strict"; var p = function(r) { if (r = r || {}, !t.isSearching) { if (t.isSearching = !0, !r.getAll) { if (t.nextPageIndex === null) { t.isSearching = !1; return } t.nextPageIndex === 1 && (t.productList = [], t.emergencyProductList = [], t.warningProductList = []) } var f = n.defer(),
                    u = { pageSize: r.getAll ? t.totalCount : t.pageSize, pageIndex: r.getAll ? 1 : t.nextPageIndex }; return t.selectedCategoryIds && t.selectedCategoryIds.length > 0 && (u.categoryIds = t.selectedCategoryIds), t.currentProducer && t.currentProducer.id !== 0 && (u.producter = t.currentProducer.itemName), t.currentSupplier && t.currentSupplier.id !== 0 && (u.dealerId = t.currentSupplier.id, u.dealerName = t.currentSupplier.name), t.searchKeyWord && (u.keyWord = t.searchKeyWord), e.getProcurementAssistantList(u).success(function(n) { if (t.isSearching = !1, r.getAll) f.resolve(n.items);
                    else { t.totalCount = n.totalCount;
                        t.urgentCount = n.urgentLackItemCount;
                        n.pageCount > t.nextPageIndex ? t.nextPageIndex++ : t.nextPageIndex = null; var u = n.items;
                        _.each(u, function(n) { n.procurementChecked = t.checkAll;
                            n.isEditing = !1;
                            n.imgUrl = n.imgUrl || "/content/imgs/default-product.png";
                            n.urgentLackCount > 0 ? t.emergencyProductList.push(n) : t.warningProductList.push(n);
                            t.productList.push(n) });
                        t.isEditing = !1;
                        i(function() { t.updateView() });
                        f.resolve(!0) } }).error(function() { c.error("获取需采购物品列表出错。");
                    t.productList = [];
                    t.emergencyProductList = [];
                    t.warningProductList = [];
                    t.isEditing = !1;
                    i(function() { t.updateView() });
                    f.reject("获取需采购物品列表出错。") }), f.promise } },
        w = function() { r.getProductCategories().then(function(n) { t.selCategoryId = 0;
                t.selCategory = { name: "全部分类", id: 0 };
                t.categoriesTree = f.unflatten(n, "showOrder");
                t.categoriesTree.splice(0, 0, t.selCategory); var i = {};
                _.each(n, function(n) { i[n.id] = n });
                t.categoryNodeMap = i }) },
        b = function() { u.dealerDic.loadActive().then(function(n) { t.currentSupplier = "所属供应商";
                n.unshift({ name: t.currentSupplier, id: 0 });
                t.suppliers = n }) },
        k = function() { u.systemItemDic.loadActive({ itemType: "库存物品品牌" }).then(function(n) { n.unshift({ itemName: "所有品牌", id: 0 });
                t.producers = n;
                t.currentProducer = "所有品牌" }) },
        d = function() { l.getGroupProcurementMethod().then(function(n) { t.groupProcurementConfig = n }) },
        g = function() { a.getOfficeOption(a.optionKeys.IsProcurementPriceLockEnabled).then(function(n) { t.isProcurementPriceLockEnabled = n }) },
        nt = function() { l.isRootGroup().then(function(n) { t.editProductPermission = n && v.isAllowed("product.productInfo") }) },
        tt = function() { a.getOfficeOption(a.optionKeys.ProcurementAssistantConfig).then(function(n) { t.procurementAssistantConfig = n }) },
        it = function() { nt();
            g();
            d();
            w();
            b();
            k();
            ut();
            tt();
            t.nextPageIndex = 1 },
        rt = function(n, i) { if (t.currentEditProduct.price = parseFloat(t.currentEditProduct.price), t.currentEditProduct.price = Math.round(t.currentEditProduct.price * 100 + 1e-5) / 100, t.isRootInGroup) { if (_.isNaN(t.currentEditProduct.price)) { c.error("报价应为数字"); return } if (t.currentEditProduct.price < 0) { c.error("报价不能小于0"); return } e.updateProcurementAssistantProduct(t.currentEditProduct).success(function() { var r = _.find(t.productList, function(n) { return n.productId === t.currentEditProduct.currentId });
                    r.isEditing = !1;
                    t.isEditing = !1;
                    n === "emergency" ? t.emergencyProductList[i] = angular.copy(t.currentEditProduct) : n === "warning" && (t.warningProductList[i] = angular.copy(t.currentEditProduct)) }) } else { var r = _.find(t.productList, function(n) { return n.productId === t.currentEditProduct.currentId });
                r.isEditing = !1;
                t.isEditing = !1;
                n === "emergency" ? t.emergencyProductList[i] = angular.copy(t.currentEditProduct) : n === "warning" && (t.warningProductList[i] = angular.copy(t.currentEditProduct)) } },
        ut = function() { r.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        ft = function(t) { var i = n.defer(); if (t && t.length > 0) s.getProductsSumCountWithRootOfficeByProductIds(t).then(function(n) { i.resolve(n.data) });
            else return null; return i.promise },
        et = function(t) { var i = n.defer(); return y.get(t).success(function(n) { n.products ? i.resolve(n.products) : i.reject() }), i.promise };
    (function() { it();
        t.search = p;
        t.saveEdit = rt;
        t.getProductsInventoryCount = ft;
        t.getProductsBySpuId = et })() }]);
supplychainModule.controller("ProcurementOrderMallCartCtrl", ["$scope", "$q", "dataHost", "$modalInstance", "permissionProvider", "procurementSvc", function(n, t, i, r, u, f) { "use strict"; var e = function(n) { console.log("closing mall frame ", n);
            r.close(n) },
        o = function() { var i = t.defer(); return u.loadPermissions().then(function(t) { if (t = _.filter(t, function(n) { return n == "stockCenter.stockViewAgreementPrice" || n == "stockCenter.stockOrderRequestNoLimit" || n == "stockCenter.stockSubmitOrderRequest" || n == "stockCenter.stockApproveOrderRequest" || n == "procurement.procurementOperateShoppingCart" || n == "procurement.procurementViewShoppingCart" }), t.length > 0) { var r = _.find(t, function(n) { return n == "procurement.procurementOperateShoppingCart" });
                    r && t.push("stockCenter.stockOperateShoppingCart");
                    r = _.find(t, function(n) { return n == "procurement.procurementViewShoppingCart" });
                    r && t.push("stockCenter.stockViewShoppingCart") } n.permissionCodes = t;
                i.resolve(!0) }), i.promise },
        s = function() { var i = t.defer(); return f.isNeedcheckPayorder(n.ownerOfficeId).then(function(t) { n.isNeedCheckPayorder = t.data;
                i.resolve(!0) }), i.promise },
        h = function() { var n = []; return n.push(o()), n.push(s()), t.all(n) };
    (function() { n.payOrderNo = i.payOrderNo;
        n.ownerOfficeId = parseInt(i.ownerOfficeId);
        n.close = e;
        n.initBasicData = h })() }]);
supplychainModule.controller("ProductCategoryEditCtrl", ["$log", "$q", "$modalInstance", "$scope", "host", "productCategorySvc", "aresNotification", function(n, t, i, r, u, f, e) { "use strict"; var o = function() { i.dismiss() },
        s = function() { r.currentLevel !== "first" && r.parentNode && (r.currentNode.parentId = r.parentNode.id);
            f.save(r.currentNode).then(function() { i.close(r.currentNode) }, function() { e.error("更新分类信息失败") }) };
    (function() { r.currentNode = angular.copy(u.currentNode);
        r.currentLevel = u.currentLevel;
        r.upperTree = u.upperTree;
        r.parentNode = u.parentNode;
        r.close = o;
        r.save = s })() }]);
supplychainModule.controller("ProductCategoryManagementCtrl", ["$log", "$scope", "$modalInstance", "$q", "$timeout", "aresTreeViewUtil", "productCategorySvc", "host", "dataDicSvc", "enums", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var v = function() { i.close(!0) },
        c, y = function() { c = s.productCategoryDic;
            t.productType == h.ProductType.DentalLab && (c = s.productCategoryDentalLabDic) },
        l = function() { var n = r.defer(); return c.refresh().then(function(i) { var r = {},
                    e, u;
                _.each(i, function(n) { r[n.id] = n;
                    _.isString(n.levelCode) && n.levelCode.length === 6 && (n.spriteCssClass = "iconfont icon-wenjianjia") });
                t.nodeMap = r;
                t.treeData = f.unflatten(i, "showOrder");
                t.passedInSelected && (e = t.passedInSelected.id, u = t.passedInSelected.parentId, u === 0 ? (t.selectedNodes.first = r[e], t.updateMoveBtnStatus("first", t.selectedNodes.first)) : u !== 0 && r[u].parentId === 0 ? (t.selectedNodes.second = r[e], t.selectedNodes.first = r[u], t.updateMoveBtnStatus("first", t.selectedNodes.first), t.updateMoveBtnStatus("second", t.selectedNodes.second)) : u !== 0 && r[r[u].parentId] && (t.selectedNodes.third = r[e], t.selectedNodes.second = r[u], t.selectedNodes.first = r[r[u].parentId], t.updateMoveBtnStatus("first", t.selectedNodes.first), t.updateMoveBtnStatus("second", t.selectedNodes.second), t.updateMoveBtnStatus("third", t.selectedNodes.third)), t.passedInSelected = null);
                t.selectedNodes.first && (t.selectedNodes.first = t.nodeMap[t.selectedNodes.first.id], t.secondLevelNodes = t.selectedNodes.first.items || []);
                t.selectedNodes.second && (t.selectedNodes.second = t.nodeMap[t.selectedNodes.second.id], t.thirdLevelNodes = t.selectedNodes.second.items || []);
                t.selectedNodes.third && (t.selectedNodes.third = t.nodeMap[t.selectedNodes.third.id]);
                n.resolve(!0) }), n.promise },
        p = function(n) { return t.productType == h.ProductType.DentalLab && (n.productType = h.ProductType.DentalLab), e.save(n) },
        w = function(n) { var r = t.nodeMap[n],
                u, i; return r.parentId === 0 ? [] : (u = t.nodeMap[r.parentId], i = [{ id: 0, name: "无" }].concat(angular.copy(t.treeData)), u.parentId === 0 ? _.each(i, function(n) { n.items = [] }) : _.each(i, function(n) { _.isArray(n.items) && _.each(n.items, function(n) { n.items = [] }) }), i) },
        b = function(n) { var t = r.defer(),
                i = _.map(n, function(n, t) { return { id: n.id, showOrder: t } }); return e.updateOrder(i).then(function() { t.resolve(!0) }, function(n) { t.reject(n) }), t.promise },
        k = function(n) { return e.delete(n.id).then(function() { return c.refresh() }) },
        d = function() { l() },
        a = function() { t.selectedNodes = { first: null, second: null, third: null };
            t.secondLevelNodes = [];
            t.thirdLevelNodes = [] };
    (function() { t.passedInSelected = o.selectedCategory;
        t.productType = o.productType;
        y();
        d();
        a();
        t.clean = v;
        t.getUpperTreeById = w;
        t.saveShowOrder = b;
        t.loadTreeData = l;
        t.saveNewCategory = p;
        t.deleteCategory = k;
        t.clearSelected = a })() }]);
supplychainModule.controller("ProductCategorySelectModalCtrl", ["$timeout", "host", "$scope", "$modalInstance", function(n, t, i, r) { "use strict"; var u = function() { r.dismiss() },
        f = function() { r.close(i.selectedCategory) };
    (function() { i.categoryTreeData = t.categoryTreeData;
        i.selectedCategory = t.selectedCategory;
        i.parentModalHeight = t.parentModalHeight;
        i.mode = t.mode || "full";
        i.close = u;
        i.confirm = f })() }]);
supplychainModule.controller("ProductBasicDataManagementCtrl", ["$scope", "$q", "$timeout", "$modal", "dataDicSvc", "systemitemSvc", "aresConfirmDialog", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function() { u.systemItemDic.load().then(function(t) { if (t) { var r = function(n) { var i = _.filter(t, function(t) { return t.itemType === n }); return _.sortBy(i, "displayOrder") },
                        u = [{ abbr: "品牌", name: "品牌管理", isCustom: !1 }, { abbr: "单位", name: "单位管理", isCustom: !1 }],
                        e = { "品牌": r("库存物品品牌"), "单位": r("库存物品单位") },
                        f = _.filter(t, function(n) { return n.itemType === "物品自由项" });
                    f = _.sortBy(f, "displayOrder");
                    _.each(f, function(n) { u.push({ abbr: n.itemName, name: n.itemValue, isCustom: !0 });
                        e[n.itemName] = r(n.itemName + "选项") });
                    n.dataTypes = u;
                    n.dataItems = e;
                    _.each(u, function(t) { if (n.selectedItem[t.abbr]) { var i = _.find(n.dataItems[t.abbr], function(i) { return i.id === n.selectedItem[t.abbr].id });
                            n.selectedItem[t.abbr] = i ? i : null } });
                    i(function() { n.initView() }) } }) },
        h = function() { s() },
        c = function(i, r) { var e = t.defer(),
                o, c, h, l; return _.some(n.dataItems[i], function(n) { return n.itemName === r }) ? (e.reject({ msg: "已经有其他项目使用此名称，请更换新名称！" }), e.promise) : (n.dataItems[i] && n.dataItems[i].length !== 0 ? (c = _.max(n.dataItems[i], function(n) { return n.displayOrder }), o = c.displayOrder + 1) : o = 1, h = i === "品牌" ? "库存物品品牌" : i === "单位" ? "库存物品单位" : i + "选项", l = { id: 0, itemName: r, itemType: h, itemTypeName: h, displayOrder: o }, f.createSystemItem(l).success(function() { u.systemItemDic.clearCache();
                s();
                e.resolve(!0) }).error(function(n) { e.reject(n) }), e.promise) },
        l = function(t) { var i = n.selectedItem[t],
                f, e;
            i && (f = _.find(n.dataTypes, function(n) { return t === n.abbr }), e = r.open({ animation: !0, backdrop: "static", template: "<inventory-system-item-edit-view><\/inventory-system-item-edit-view>", controller: "InventorySystemItemEditCtrl", size: "sm", resolve: { host: function() { return { systemsettingId: i.id, parentCatagoryId: -1, siblings: n.dataItems[t], dataTypeName: f.name, currentSystemItem: angular.copy(n.selectedItem[t]) } } } }), e.result.then(function() { u.systemItemDic.clearCache();
                s() })) },
        a = function(t) { var i = n.selectedItem[t];
            i && e.warn({ message: "确定要删除此配置？", showCancelBtn: !0 }).then(function() { f.deleteSystemItem(i.id).success(function() { o.success("删除成功！");
                    u.systemItemDic.clearCache();
                    s() }).error(function(n) { if (n.name === "SystemItemUsedException") { var t = i.itemName;
                        e.warn({ message: "【" + t + "】已被产品使用,不能删除！" }); return } e.warn({ message: "删除失败" }) }) }) },
        v = function(t) { f.updateSystemItemList(n.dataItems[t]).success(function() { u.systemItemDic.refresh();
                o.success("排序保存成功！") }) };
    (function() { n.newItemName = {};
        n.selectedItem = {};
        n.addItem = c;
        n.deleteItem = a;
        n.editItem = l;
        n.updateList = v;
        h() })() }]);
supplychainModule.controller("ProductSystemItemCtrl", ["$log", "$scope", "$timeout", "$modal", "constants", "systemitemSvc", "aresConfirmDialog", "dataDicSvc", "aresNotification", function(n, t, i, r, u, f, e, o, s) { "use strict"; var h, l = [{ key: 1, name: "库存物品单位" }, { key: 2, name: "库存物品品牌" }, { key: 3, name: "库存物品类别" }, ],
        a = function() { t.itemType = _.find(l, { key: t.key });
            c() },
        c = function() { t.itemType ? o.systemItemDic.load().then(function(n) { if (n) { var i = _.filter(n, { itemType: t.itemType.name });
                    i = _.sortBy(i, "displayOrder");
                    angular.forEach(i, function(n, t) { n.displayOrder = t + 1 });
                    t.systemItems = i } }) : n.log("key: " + t.key) },
        v = function() { var n = _.findIndex(u.systemItemTypeList, { key: t.itemType.name }),
                i = r.open({ animation: !0, backdrop: "static", template: "<inventory-system-item-edit-view><\/inventory-system-item-edit-view>", controller: "InventorySystemItemEditCtrl", size: "sm", resolve: { host: function() { return { systemsettingId: 0, parentCatagoryId: n, displayOrder: t.systemItems.length } } } });
            i.result.then(function() { o.systemItemDic.clearCache();
                o.producerDic.clearCache();
                c() }) },
        y = function(n) { var t = r.open({ animation: !0, backdrop: "static", template: "<inventory-system-item-edit-view><\/inventory-system-item-edit-view>", controller: "InventorySystemItemEditCtrl", size: "sm", resolve: { host: function() { return { systemsettingId: n.id, parentCatagoryId: -1 } } } });
            t.result.then(function() { o.systemItemDic.clearCache();
                o.producerDic.clearCache();
                c() }) },
        p = function() { h && i.cancel(h);
            t.isDisableMoveBtn = !1;
            h = i(function() { f.updateSystemItemList(t.systemItems).success(function() { o.systemItemDic.refresh();
                    o.producerDic.refresh() }) }, 2e3) },
        w = function(n) { e.confirm({ message: "确定要删除此配置？" }).then(function() { f.deleteSystemItem(n.id).success(function() { s.success("删除成功！");
                    o.systemItemDic.clearCache();
                    o.producerDic.clearCache();
                    c() }).error(function(t) { if (t.name === "SystemItemUsedException") { var i = n.itemName;
                        e.warn({ message: "【" + i + "】已被产品使用,不能删除！" }); return } e.warn({ message: "删除失败" }) }) }) };
    (function() { t.updateList = p;
        t.createSystemItem = v;
        t.editSystemItem = y;
        t.deleteSystemItem = w;
        a();
        t.$on("$destroy", function() { h && i.cancel(h);
            t.systemItems && f.updateSystemItemList(t.systemItems).success(function() { o.systemItemDic.refresh();
                o.producerDic.refresh() }) }) })() }]);
supplychainModule.controller("InventoryProductUnityListCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$sce", "aresConfirmDialog", "aresNotification", "productUnitySvc", "inventorySvc", "dataDicSvc", "enums", "organizationSvc", "productWarnRuleSvc", "productCategorySvc", "aresTreeViewUtil", "inventoryUtil", "loginContext", "officeUtil", "officeSvc", "moduleOptionProvider", "officeSelectorUtil", "productSvc", "aresDialog", function(n, t, i, r, u, f, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt) { "use strict"; var ni = function() { var n = u.defer(); return l.systemItemDic.loadActive({ itemType: "库存物品类别" }).then(function(i) { t.categories = i;
                t.categories.splice(0, 0, { id: 0, itemName: "所属大类" });
                n.resolve(!0) }), n.promise },
        st = function() { var n = u.defer(); return l.dealerDic.loadActive().then(function(i) { t.dealers = i;
                t.dealers.splice(0, 0, { id: 0, name: "所属供应商" });
                n.resolve(!0) }), n.promise },
        ht = function() { return g.getSelfAndChildOfficesByGroupId(k.officeId, !1).success(function(n) { var i = tt.setId(n),
                    r = [];
                et(i, r);
                t.allOfficeIds = r;
                t.officeTreeData = i }) },
        et = function(n, t) { _.each(n, function(n) { t.push(n.id);
                n.isGroup && n.parentId !== 0 && (n.isGroup = !1);
                n.hasChildren && et(n.items, t) }) },
        ut = function() { var n = u.defer(),
                i = { pageIndex: t.page.index, pageSize: t.page.size, category: t.selCategory, dealerId: t.selDealerId, searchText: t.searchKeywords, isWithProducts: !0, isEnabled: t.enableStatus, isProductWarnEnabled: t.selIsProductWarnEnabled, valuationType: t.selValuationType, isCritical: t.selIsCritical, categoriesIds: b.getAllSubCategoriesIds(t.selectedCategory), isMatchBaseLcSPU: t.isMatchBaseLcSPU }; return t.selectedOfficeIds.length > 0 && (i.availableOfficeId = t.selectedOfficeIds[0].officeId), h.search(i).success(function(i) { t.productUnityList = i.items;
                t.page.index = i.pageIndex;
                t.page.totalCount = i.totalCount;
                t.page.pageCount = i.pageCount;
                ct(t.productUnityList);
                r(function() { t.initTableView();
                    t.scrollToTop();
                    t.showEmptyWithAdd = t.selectedCategory && !t.searchKeywords && (t.selValuationType == "null" || t.selValuationType == null) && t.selDealerId == 0 && (t.selIsProductWarnEnabled == "null" || t.selIsProductWarnEnabled == null) && t.enableStatus && (t.selIsCritical == "null" || t.selIsCritical == null) });
                n.resolve() }), t.canChangeCategory = !1, n.promise },
        ct = function(n) { _.each(n, function(n) { n.specifications = _.map(n.products, function(n) { return { specification: n.specification, unit: n.unit, code: n.code } });
                n.categoryBreadcrumb = t.getCategoryBreadcrumbHtml(n) }) },
        lt = function(n) { n && o.confirm({ message: "确定要删除此物品？" }).then(function() { h.delete(n).success(function(n) { n ? (s.success("删除成功！"), ut(), t.isShowHandleBtn && ft()) : s.error("删除失败:" + e.message) }).error(function(n) { s.error(n.message) }) }) },
        ot = function() { var n = u.defer(); return l.productCategoryDic.load().then(function(i) { var u = {};
                _.each(i, function(n) { u[n.id] = n;
                    _.isString(n.levelCode) && (n.levelCode.length === 6 && (n.spriteCssClass = "iconfont icon-wenjianjia"), n.levelCode.length === 9 && (n.spriteCssClass = "iconfont icon-icon-test")) });
                t.categoryNodeMap = u;
                t.categoryTreeData = w.unflatten(i, "showOrder");
                t.selectedCategory && (t.categoryNodeMap[t.selectedCategory.id] ? r(function() { t.categoryTreeInstance && t.categoryTreeInstance.selectById(t.selectedCategory.id) }) : (t.selectedCategory = null, t.categoryTreeInstance && t.categoryTreeInstance.select($())));
                n.resolve(!0) }), r(function() { t.initTreeView() }), n.promise },
        at = function(n) { var i = _.filter(t.productUnityList, function(n) { return n.changeCategoryChecked }),
                r = _.map(i, function(n) { return n.id }); return h.updateCategory({ ids: r, categoryId: n.id }) },
        vt = function(n) { return h.saveProductOffices(n) },
        yt = [{ id: null, name: "计价方式" }, { id: 0, name: "移动加权平均法" }, { id: 1, name: "个别计价法" }],
        pt = [{ id: null, name: "物品预警" }, { id: !0, name: "开启" }, { id: !1, name: "关闭" }],
        wt = [{ id: null, name: "是否为高值耗材" }, { id: !0, name: "是" }, { id: !1, name: "否" }],
        bt = function() { return d.isRootGroup().then(function(n) { t.isShowHandleBtn = k.isGroup && n || !k.isGroup || k.isGroup && !k.isRegularChain;
                t.isRootGroup = n }) },
        kt = function() { return b.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        ft = function() { h.search({ pageIndex: 1, pageSize: 1, isEnabled: !0, isMatchBaseLcSPU: !0 }).success(function(n) { t.replaceableSpuCount = n.totalCount }) },
        dt = function(n) { h.ignoreProductUntiyMatch(n).success(function(n) { n ? (ut().then(function() { t.isMatchBaseLcSPU && t.productUnityList.length === 0 && (t.isMatchBaseLcSPU = !1, ut()) }), ft(), s.success("保存成功")) : s.error("保存失败") }) },
        gt = function() { var r = { pageIndex: t.page.index, pageSize: t.page.size, category: t.selCategory, dealerId: t.selDealerId, searchText: t.searchKeywords, isWithProducts: !0, isEnabled: t.enableStatus, isProductWarnEnabled: t.selIsProductWarnEnabled, valuationType: t.selValuationType, isCritical: t.selIsCritical, categoriesIds: b.getAllSubCategoriesIds(t.selectedCategory), isMatchBaseLcSPU: t.isMatchBaseLcSPU },
                n = { criteria: r, columns: [{ field: "category1", group: "物品分类信息", hidden: !1, title: "一级分类", width: "200px" }, { field: "category2", group: "物品分类信息", hidden: !1, title: "二级分类", width: "200px" }, { field: "category3", group: "物品分类信息", hidden: !1, title: "三级分类", width: "200px" }, { field: "lcMallCode", group: "交易平台", hidden: !1, title: "领健商城编码", width: "200px" }, { field: "Name", group: "物品基础信息", hidden: !1, title: "名称", width: "250px" }, { field: "producer", group: "物品基础信息", hidden: !1, title: "品牌", width: "150px" }, { field: "Specification", group: "物品基础信息", hidden: !1, title: "规格", width: "250px" }, { field: "unit", group: "物品基础信息", hidden: !1, title: "单位", width: "50px" }, { field: "isPackage", group: "物品拆包信息", hidden: !1, title: "是否大包装", width: "60px" }, { field: "packageCount", group: "物品拆包信息", hidden: !1, title: "换算数量", width: "50px" }, { field: "sfdaCode", group: "物品属性", hidden: !1, title: "药（械）准字", width: "200px" }, { field: "code", group: "物品属性", hidden: !1, title: "内部编码", width: "200px" }, { field: "barCode", group: "物品属性", hidden: !1, title: "条形码", width: "200px" }, { field: "preferredDealer", group: "采购价设置", hidden: !1, title: "首选供应商", width: "250px" }, { field: "preferredDealerPrice", group: "采购价设置", hidden: !1, title: "首选供应商报价", width: "150px" }, { field: "dealer2", group: "采购价设置", hidden: !1, title: "供应商2", width: "250px" }, { field: "dealer2Price", group: "采购价设置", hidden: !1, title: "供应商2报价", width: "150px" }, { field: "dealer3", group: "采购价设置", hidden: !1, title: "供应商3", width: "250px" }, { field: "dealer3Price", group: "采购价设置", hidden: !1, title: "供应商3报价", width: "150px" }, { field: "salesPrice", group: "销售价设置", hidden: !1, title: "价格", width: "100px" }, { field: "isBatchNoEnabled", group: "高级", hidden: !1, title: "批号管理", width: "100px" }, { field: "isExpiredDateEnabled", group: "高级", hidden: !1, title: "有效期管理", width: "100px" }, { field: "valuationType", group: "高级", hidden: !1, title: "个别计价", width: "100px" }, { field: "freeField1", group: "自由项", hidden: !1, title: "自由项1", width: "150px" }, { field: "freeField2", group: "自由项", hidden: !1, title: "自由项2", width: "150px" }, { field: "freeField3", group: "自由项", hidden: !1, title: "自由项3", width: "150px" }] },
                i = 1e3;
            t.page.totalCount >= i ? rt.confirm("提示", "记录超过" + i + "条，创建我的报表，是否继续？").then(function() { h.createExportProductBackground(n).success(function(n) { var t = n.isSucceed ? n.hasTaskCancelled ? "后台报表'" + n.newTask.reportName + "'已创建！（已取消10分钟内同类报表）" : "后台报表'" + n.newTask.reportName + "'已创建！" : "已存在处理的同类型的报表（10分钟内只能创建一个同类型报表）！";
                    rt.info("信息", t) }) }) : h.exportProduct(n) };
    (function() { t.isShowHandleBtn = !1;
        t.isShowOfficeBatch = k.isGroup && k.isRootGroup;
        ot().then(function() { ht();
            st().then(function() { t.enableStatus = !0;
                t.selDealerId = 0;
                t.selValuationType = null;
                t.selIsCritical = null;
                t.selIsProductWarnEnabled = null;
                t.isMatchBaseLcSPU = !1;
                bt().then(function() { t.isShowHandleBtn && ft() });
                ut() }) });
        t.search = ut;
        t.deleteProductUnity = lt;
        t.enableStatus = !0;
        t.searchKeywords = "";
        t.page = { index: 1, size: 20, totalCount: 100 };
        t.selectedCategory = null;
        t.pricingMethodDropdownData = yt;
        t.productWarningDropdownData = pt;
        t.isCriticalDropdownData = wt;
        t.initProductCategoryData = ot;
        t.updateCategory = at;
        t.saveProductOffices = vt;
        t.initProductCodeOptions = kt;
        t.getReplaceableSpuCount = ft;
        t.ignoreProductUntiyMatch = dt;
        t.exportProduct = gt })() }]);
supplychainModule.controller("ProductRemindConfigCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "aresDialog", "host", "productWarnRuleSvc", "aresNotification", "dataDicSvc", "enums", "inventoryUtil", "productSvc", "officeOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { "use strict"; var p = function() { var i = u.defer(); return s.get(o.productUnityId).success(function(n) { t.productWarnRule = n;
                w(t.productWarnRule);
                t.products = n.products;
                b(t.products);
                i.resolve(!0) }).error(function(t) { n.log(t.message);
                i.reject() }), i.promise },
        w = function(n) { if (!n.warehouseProductOptions) { var i = { warehouseId: 0, lowLimit: t.inventoryCountLowLimit };
                n.warehouseProductOptions = [i] } },
        b = function(n) { angular.forEach(n, function(n) { n.name = n.specAndUnit }) },
        k = function() { f.dismiss() },
        d = function() { t.productWarnRule && g() && s.save(t.productWarnRule).success(function(n) { t.productWarnRule = n;
                h.success("保存成功！");
                f.close(n) }).error(function(t) { n.log(t.message);
                h.error("保存失败:" + t.message);
                p() }) },
        g = function() { var n, r, i, u; if (!Ares.ensureNotDuplicated("ProductRemindConfigCheck")) return !1; if (!t.productWarnRule) return h.error("当前物品不存在"), !1; if (n = angular.copy(t.productWarnRule.productIds), r = _.isString(n) ? n.split(",") : n, r.length == 0 || n == "") return h.error("请选择规格"), !1; if (t.productWarnRule.warnMethod == l.ProductWarnMethod.BySingle && (!t.productWarnRule.ruleData || t.productWarnRule.ruleData == "0")) return h.error("预警值不正确"), !1; if (t.productWarnRule.warnMethod == l.ProductWarnMethod.ByWarehouse) { if (!t.productWarnRule.warehouseProductOptions || t.productWarnRule.warehouseProductOptions.length == 0 || (i = _.find(t.productWarnRule.warehouseProductOptions, function(n) { return !Number(n.warehouseId) }), i)) return h.error("请设置仓库预警"), !1; if (i = _.find(t.productWarnRule.warehouseProductOptions, function(n) { return !n.lowLimit }), i) return u = _.find(t.warehouses, function(n) { return n.id == i.warehouseId }), h.error("【" + u.name + "】预警值不正确"), !1 } return !0 },
        nt = function() { var n = u.defer(); return y.getOfficeOption(y.optionKeys.IsInventoryCountWarnEnabled).then(function(i) { t.isInventoryCountWarnEnabled = i;
                y.getOfficeOption(y.optionKeys.InventoryCountLowLimit).then(function(i) { t.InventoryCountLowLimit = i;
                    t.inventoryCountLowLimit = t.isInventoryCountWarnEnabled ? i : 5;
                    t.inventoryCountLowLimitStr = t.isInventoryCountWarnEnabled ? i : "未配置";
                    n.resolve(!0) }) }), n.promise },
        tt = function() { nt().then(function() { a.initWarehouses().then(function(n) { t.warehouses = n;
                    t.warehouses && t.warehouses.splice(0, 0, { id: 0, name: "请选择仓库" });
                    p() }) }) };
    (function() { t.save = d;
        t.close = k;
        tt() })() }]);
supplychainModule.controller("InventoryMgmtSalesOrderListCtrl", ["$log", "$q", "$timeout", "$scope", "aresNotification", "inventorySvc", "enums", "dataDicSvc", "reportUtil", function(n, t, i, r, u, f, e, o, s) { "use strict"; var h = function() { var n = angular.copy(r.searchCriteria),
                i; return n.status == "all" && (n.status = null), n.startDate = moment(n.startDate).format("YYYY-MM-DD"), n.endDate = moment(n.endDate).add(1, "days").format("YYYY-MM-DD"), i = t.defer(), f.searchInventoryMgmtSalesOrder(n).then(function(n) { var t = n.data;
                r.salesOrderList = t.items;
                r.salesOrderTotalCount = t.totalCount;
                i.resolve() }), i.promise },
        c = function() { l();
            o.currentOfficeWorkProviderDic.load().then(function(n) { r.workInOfficeProviders = n });
            h().then(function() { i(function() { r.initTableView() }) }) },
        l = function() { var n = s.getDefaultTimeSpan().startTime,
                t = s.getDefaultTimeSpan().endTime;
            r.searchCriteria = { startDate: n, endDate: t, status: "all", billNo: "", sellerId: 0, pageIndex: 0, pageSize: 10 } };
    (function() { r.InventorySalesStatus = e.InventorySalesStatus;
        r.searchSalesOrder = h;
        c() })() }]);
supplychainModule.controller("SupplierEditCtrl", ["$log", "$scope", "$q", "$modalInstance", "$modal", "organizationSvc", "pictureSvc", "dataDicSvc", "dataHost", "aresConfirmDialog", "aresNotification", "enums", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; var v = [],
        a = s.organizationType,
        b = { isDealer: a != l.OrganizationType.DentalLabFactory, isDisabled: !1, isEnabled: !0, type: a, certificatePicture: [], qualificationPicture: [], settlementMethod: a == l.OrganizationType.DentalLabFactory ? 1 : 0 },
        k = function(n) { if (n.organizationPictures = n.qualificationPicture.concat(n.certificatePicture), n.expiredDate && (n.expiredDate = moment(n.expiredDate).format("YYYY-MM-DD")), t.code && (t.supplier.code = t.code), Ares.ensureNotDuplicated("SaveAppt")) { var i = p() ? f.update : f.add;
                i(n).success(function(n) { _.each(_.unique(v, !1), function(n) { e.destroyPicture(n) });
                    c.success("保存成功!");
                    o.dealerDic.refresh();
                    r.close(n);
                    Ares.sensors.track("SupplierEditCtrl", { PatientName: t.supplier.name, OperationType: "保存" }) }).error(function(i) { if (i.name === "OrganizationNameNotUniqueException") { var r = "名称：" + n.name;
                        h.warn({ message: "" + t.supplierName + "【" + r + "】已经存在！" }) } else i.name === "ProductDealerException" && h.warn({ message: "该" + t.supplierName + "已被设置为某些物品的首选" + t.supplierName + "，无法设置为未启用！" }) }) } },
        d = function() { var n = s.supplier,
                i = s.isNotLcView;
            t.isNotLcView = i;
            t.isEditPicture = !i;
            n && n.id ? f.get(n.id).success(function(n) { _.each(n.organizationPictures, function(n) { w(n) }); var i = _.groupBy(n.organizationPictures, "pictureName");
                n.certificatePicture = i.organizationCertificate || [];
                n.qualificationPicture = i.organizationQualification || [];
                t.supplier = n;
                t.supplier.isEnabled = !t.supplier.isDisabled;
                t.isLinkedCare = t.supplier.type != l.OrganizationType.NormalDealer && t.supplier.type != l.OrganizationType.DentalLabFactory }) : (n = n || angular.copy(b), t.supplier = n, t.isLinkedCare = t.supplier.type != l.OrganizationType.NormalDealer && t.supplier.type != l.OrganizationType.DentalLabFactory) },
        p = function() { return t.supplier && !!t.supplier.id },
        g = function() { r.dismiss("close") },
        y = function(n, i, r) { if (r.delete) { _.each(angular.copy(n), function(t, i) { if (t.pictureId === r.pictureId) { n.splice(i, 1);
                        v.push(r.pictureId); return } }); return } var u = {};
            u.id = 0;
            u.targetId = 0;
            u.pictureName = i;
            u.pictureId = r.id;
            typeof r.editId == "number" ? (v.push(n[r.editId].pictureId), n[r.editId].pictureId = r.id) : n.push(u);
            w(u);
            t.initBasicTabScrollbar(t.paperTabContainer) },
        nt = function(n) { y(t.supplier.qualificationPicture, "organizationQualification", n) },
        tt = function(n) { y(t.supplier.certificatePicture, "organizationCertificate", n) },
        w = function(n) { n.pictureId && e.getPicture(n.pictureId).success(function(t) { t && t.filePath && (n.filePath = encodeURIComponent(t.filePath)) }) };
    (function() { t.isEdit = p;
        t.updateQualificationPicture = nt;
        t.updateCertificatePicture = tt;
        t.updatePicture = y;
        t.saveSupplier = k;
        t.supplierName = a == l.OrganizationType.DentalLabFactory ? "厂商" : "供应商";
        t.close = g;
        d() })() }]);
supplychainModule.controller("SupplierListCtrl", ["$log", "$scope", "$modal", "$filter", "$timeout", "$q", "organizationSvc", "aresConfirmDialog", "dataDicSvc", "aresNotification", "formatUtil", "aresModalShelf", "officeUtil", "enums", "inventoryUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { "use strict"; var w = function() { var n = f.defer(); return a.isRootGroup().then(function(i) { i && (t.isShowRootElement = i, n.resolve(!0)) }), n.promise },
        y = function() { var n = { pageIndex: t.page.index, pageSize: t.page.size, name: t.name, isEnabled: null }; if (t.enableStatus == 1) n.isEnabled = !0;
            else if (t.enableStatus == 2) n.isEnabled = !1;
            else if (t.enableStatus == 3) n.isEnabled = null;
            else { t.suppliers = [];
                t.page.index = 1;
                t.page.totalCount = 0; return } e.searchOrganizationPageList(n).success(function(n) { t.suppliers = n.items;
                t.page.index = n.pageIndex;
                t.page.totalCount = n.totalCount;
                c.formatList(t.suppliers, { isDealer: "boolStr", isProducer: "boolStr" });
                angular.forEach(t.suppliers, function(n) { n.isDisabledStr = n.isDisabled ? "否" : "是";
                    n.expiredDate && moment(n.expiredDate).isBefore(new Date, "day") && (n.addWarnStyle = !0) });
                u(function() { t.initTableView();
                    t.scrollToTop() }) }) },
        b = function() { p(null).then(function() { y() }) },
        k = function(n, i) { t.isNotLcView = i ? i : !1;
            p(n).then(function() { y() }) },
        d = function(n) { var t = n.name;
            o.confirm({ message: "确认要删除供应商【" + t + "】？" }).then(function() { e.destroySupplier(n.id).success(function() { y();
                    s.dealerDic.refresh();
                    h.success("删除成功!") }).error(function(n) { n.name == "OrganizationNameIsUsedException" && o.warn({ message: "此供应商已被使用过不能删除，您可以设置供应商为不启用！" }) }) }) },
        p = function(n) { var i = "新增供应商",
                r; return n && !t.isNotLcView ? i = "编辑供应商" : n && t.isNotLcView && (i = "查看供应商"), r = l.open({ template: "<supplier-edit-view><\/supplier-edit-view>", controller: "SupplierEditCtrl", title: i, titleIconClass: "iconfont icon-gongyingshang", resolve: { dataHost: function() { return { supplier: n, isNotLcView: t.isNotLcView, organizationType: v.OrganizationType.NormalDealer } } }, needActive: !0, confirmClose: !n }), r.result },
        g = function() { e.exportOrganizationTemplate("供应商导入模板.xls") };
    (function() { t.searchText = null;
        t.addSupplier = b;
        t.editSupplier = k;
        t.deleteSupplier = d;
        t.downSupplierTemplate = g;
        t.search = y;
        t.enableStatus = 1;
        t.page = { index: 1, size: 20 };
        w();
        y() })() }]);
supplychainModule.directive("inventoryProductCheckEditView", ["$log", "eventAggregator", "$timeout", "dataDicSvc", function(n, t, i, r) { "use strict"; return { templateUrl: "/app/supplychain/dialogs/inventory-check-order-edit-dialog/inventory-product-check-edit-view.html", replace: !0, link: function(n, t) { var u = function() { var t = n.inventoryCheckOrder.items[0].details[0].actualCount * 1;
                    n.inventoryCheckOrder.items[0].details[0].actualCount = _.isNumber(t) && !_.isNaN(t) ? t < 0 ? 0 : t : "" },
                f = function() { r.currentOfficeWorkProviderDic.load().then(function(i) { i.unshift({ id: 0, name: "请选择盘点人" });
                        t.find("#receiverInput-drop").kendoDropDownList({ dataSource: i, filter: "contains", dataTextField: "name", dataValueField: "id", select: function(t) { n.inventoryCheckOrder.checkerId = this.dataItem(t.item)[this.options.dataValueField] || null } }) }) },
                e = function() { var t = n.inventoryCheckOrder.items[0].details[0].actualCount * 1;
                    t && t >= 0 ? (t -= 1, n.inventoryCheckOrder.items[0].details[0].actualCount = t) : n.inventoryCheckOrder.items[0].details[0].actualCount = 0;
                    event.preventDefault() },
                o = function() { var t = n.inventoryCheckOrder.items[0].details[0].actualCount * 1;
                    t ? t += 1 : t = 1;
                    n.inventoryCheckOrder.items[0].details[0].actualCount = t;
                    event.preventDefault() },
                s = function() { n.inventoryCheckOrder.checkerId <= 0 && f() };
            (function() { n.onCountChanged = u;
                n.reduceNum = e;
                n.plusNum = o;
                s();
                i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 5) })() } } }]);
supplychainModule.controller("InventoryProductCheckEditCtrl", ["$log", "$scope", "$modalInstance", "aresNotification", "inventorySvc", "host", "inventoryUtil", "aresConfirmDialog", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function() { i.dismiss() },
        h = function() { Ares.ensureNotDuplicated("InventoryCheckOrderSaveCheck") && o.confirm({ message: "您确定执行该单据吗？单据执行后库存将发生变更" }).then(function() { var n = t.inventoryCheckOrder.items[0].details[0].actualCount,
                    f; if (!n && n !== 0) { r.error("请输入盘点数量"); return } if (n = n * 1, _.isNaN(n) || !_.isNumber(n)) { r.error("请输入盘点数量"); return } if (n > 1 && t.inventoryCheckOrder.items[0].details[0].unicode) { r.error("当前物品为高值耗材且开启了唯一码管理，盘点数设置有误"); return } if (t.inventoryCheckOrder.items[0].actualCount = n, n == t.inventoryCheckOrder.inventoryCount) { r.error("当前库存数和盘点数一样，无需盘点"); return } if (f = t.inventoryCheckOrder.checkerId * 1, f <= 0) { r.error("请选择盘点人"); return } t.inventoryCheckOrder.items[0].details[0].notes = t.inventoryCheckOrder.notes;
                u.addCheckOrder(t.inventoryCheckOrder).success(function(n) { u.approveCheckOrder(n.id).success(function() { r.success("操作成功!");
                        i.close(t.inventoryCheckOrder.items[0].actualCount);
                        Ares.sensors.track("InventoryOperation", { OrderNumber: n.orderNumber, OperationType: "盘点", OperationMode: "保存并执行" }) }).error(function(n) { e.showInventoryErrorMessage(n, "盘点失败") }) }).error(function(n) { e.showInventoryErrorMessage(n, "保存失败") }) }) };
    (function() { t.inventoryCheckOrder = f.inventoryCheckOrder;
        t.isAdmin = t.inventoryCheckOrder.checkerId <= 0;
        t.close = s;
        t.save = h })() }]);
supplychainModule.directive("inventoryInOrderCountView", ["$log", "$modal", "$timeout", "loginContext", function(n, t, i) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/dialogs/inventory-in-order-count-dialog/inventory-in-order-count-view.html", link: function(n, t) {
            (function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 5) })() } } }]);
supplychainModule.controller("InventoryInOrderCountCtrl", ["$q", "$log", "$scope", "$modalInstance", "host", "loginContext", "aresNotification", "procurementSvc", "aresDialog", function(n, t, i, r, u) { "use strict"; var f = function() { r.close(!1) };
    (function() { i.close = f;
        i.orderItem = u.orderItem;
        i.isInventoryCostVisible = u.isInventoryCostVisible;
        i.isExpireDateVisible = u.orderItem.batches.some(function(n) { return n.expiredDate });
        i.isBatchNumberVisible = u.orderItem.batches.some(function(n) { return n.batchNumber });
        i.isUnicodeVisible = u.orderItem.batches.some(function(n) { return n.unicode });
        i.printProductLabel = u.printProductLabel })() }]);
supplychainModule.directive("inventoryProductPackView", ["$log", "$modal", "$timeout", "loginContext", "moduleOptionProvider", function(n, t, i, r) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/dialogs/inventory-product-batch-dialog/inventory-product-pack-view.html", link: function(n, t) { var f = function() { var n = t.find(".inventory-product-pack-rules-select-wrapper");
                    n.tooltip({ title: "合包数量不足", trigger: "manual", placement: "top" }).tooltip("show");
                    i(function() { n.tooltip("hide") }, 1e3) },
                e = function(t) { var r = n.packageRules[t.item[0].dataset.offsetIndex];
                    n.productBatch.maxCount && r.count > n.productBatch.maxCount ? (f(), t.preventDefault()) : (n.lastSelectedPackageRule = angular.copy(n.selectedPackageRule), i(function() { n.updateProductBatchWithRule();
                        n.sliderInstance.update();
                        u() })) },
                u = function() { n.sliderInstance && n.sliderInstance.value(n.productBatch.packCount);
                    n.productBatch.amount = n.productBatch.packCount === n.currentInventoryItem.totalCount ? n.productBatch.copyAmount : n.productBatch.packCount * n.productBatch.price };
            (function() { n.onPackCountChange = u;
                n.onPackRuleSelect = e;
                n.isInventoryCostVisible = r.isInventoryCostAllowed;
                i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 5) })() } } }]);
supplychainModule.controller("InventoryProductPackCtrl", ["$q", "$log", "$scope", "$modalInstance", "$filter", "host", "enums", "loginContext", "aresNotification", "productUnitySvc", "inventorySvc", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; var v = function() { r.close(!1) },
        y = function() { var n = i.productBatch.packCount / i.selectedPackageRule.count,
                t, u; if (!n || n % 1 != 0) { t = "合包后数量必须为大于0的整数！";
                l.warn({ message: t }); return } u = { fromProductId: i.productBatch.productId, toProductId: i.productBatch.toProductId, count: n, toPackageCount: i.productBatch.toPackageCount, warehouseId: i.productBatch.warehouseId, fromBatchNumber: i.productBatch.batchNumber, fromExpiredDate: i.productBatch.expiredDate, toBatchNumber: i.productBatch.batchNumber, toExpiredDate: i.productBatch.expiredDate, packageType: 1 };
            c.packageProduct(u).success(function(n) { s.success("合包成功");
                r.close(n) }).error(function(n) { n.message ? s.error(n.message) : s.error("合包失败") }) },
        p = function() { var n = f.batchIndex || 0;
            i.currentInventoryItem = angular.copy(f.currentInventoryItem);
            i.currentInventoryItem.totalCount = angular.isDefined(n) ? i.currentInventoryItem.batches[n].count : i.currentInventoryItem.count;
            i.packageRules = angular.copy(f.packageRules);
            i.selectedPackageRule = _.find(i.packageRules, function(n) { return i.currentInventoryItem.totalCount >= n.count });
            i.lastSelectedPackageRule = angular.copy(i.selectedPackageRule);
            i.productBatch = { name: i.currentInventoryItem.product.name, productId: i.currentInventoryItem.productId, warehouseId: i.currentInventoryItem.warehouseId, batchNumber: i.currentInventoryItem.batches[n].batchNumber, expiredDate: i.currentInventoryItem.batches[n].expiredDate, price: i.currentInventoryItem.product.valuationType === 1 ? i.currentInventoryItem.batches[n].price : i.currentInventoryItem.price, unit: i.currentInventoryItem.product.unit, code: i.currentInventoryItem.product.code, specification: i.currentInventoryItem.product.specification };
            i.productBatch.copyAmount = i.currentInventoryItem.amount },
        a = function() { i.productBatch.maxCount = Math.floor(i.currentInventoryItem.totalCount / i.selectedPackageRule.count) * i.selectedPackageRule.count;
            i.productBatch.packCount = i.selectedPackageRule.count;
            i.productBatch.isPackage = i.selectedPackageRule.isPackage;
            i.productBatch.toPackageCount = i.selectedPackageRule.count;
            i.productBatch.toProductId = i.selectedPackageRule.fromProductId;
            i.productBatch.toSpecification = i.selectedPackageRule.fromSpecification;
            i.productBatch.toUnit = i.selectedPackageRule.fromUnit;
            i.productBatch.toPrice = i.selectedPackageRule.toPrice;
            i.productBatch.toCode = i.selectedPackageRule.toCode;
            i.productBatch.toNumber = i.selectedPackageRule.toNumber;
            i.productBatch.amount = i.productBatch.packCount === i.currentInventoryItem.totalCount ? i.productBatch.copyAmount : i.productBatch.packCount * i.productBatch.price };
    (function() { p();
        a();
        i.updateProductBatchWithRule = a;
        i.close = v;
        i.save = y })() }]);
supplychainModule.directive("inventoryProductUnpackView", ["$log", "$modal", "$timeout", "loginContext", "moduleOptionProvider", function(n, t, i, r) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/dialogs/inventory-product-batch-dialog/inventory-product-unpack-view.html", link: function(n, t) { var u = function() { n.sliderInstance && n.sliderInstance.value(n.productBatch.unpackCount);
                n.productBatch.amount = n.productBatch.unpackCount * n.productBatch.price > n.productBatch.copyAmount ? n.productBatch.copyAmount : n.productBatch.unpackCount * n.productBatch.price;
                n.productBatch.amount = n.productBatch.unpackCount === n.currentInventoryItem.totalCount ? n.productBatch.copyAmount : n.productBatch.unpackCount * n.productBatch.price };
            (function() { n.onUnpackCountChange = u;
                n.isInventoryCostVisible = r.isInventoryCostAllowed;
                i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 5) })() } } }]);
supplychainModule.controller("InventoryProductUnpackCtrl", ["$q", "$log", "$scope", "$modalInstance", "$filter", "host", "enums", "loginContext", "aresNotification", "productUnitySvc", "inventorySvc", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; var a = function() { r.close(!1) },
        v = function() { var u = i.productBatch.name,
                n, t; if (!i.productBatch.unpackCount || i.productBatch.unpackCount == 0) { n = "物品【" + u + "】数量必须大于0！";
                l.warn({ message: n }); return } t = { fromProductId: i.productBatch.productId, toProductId: i.productBatch.toProductId, count: i.productBatch.unpackCount, toPackageCount: i.productBatch.toPackageCount, warehouseId: i.productBatch.warehouseId, fromBatchNumber: i.productBatch.batchNumber, fromExpiredDate: i.productBatch.expiredDate, toBatchNumber: i.productBatch.batchNumber, toExpiredDate: i.productBatch.expiredDate, packageType: 0 };
            c.packageProduct(t).success(function(n) { s.success("拆包成功");
                r.close(n) }).error(function(n) { n.message ? s.error(n.message) : s.error("拆包失败") }) },
        y = function() { var n = i.productBatch.productId;
            h.getProductPackage(n).success(function(n) { n && (i.productBatch.isPackage = n.isPackage, i.productBatch.toPackageCount = n.count, i.productBatch.toProductId = n.toProductId, i.productBatch.toSpecification = n.toSpecification, i.productBatch.toUnit = n.toUnit, i.productBatch.toPrice = n.toPrice, i.productBatch.toCode = n.toCode, i.productBatch.toNumber = n.toNumber) }) };
    (function() { var n, t, r;
        i.close = a;
        i.save = v;
        n = angular.copy(f.currentInventoryItem);
        t = f.batchIndex;
        n.totalCount = angular.isDefined(t) ? n.batches[t].count : n.count;
        r = n.batches[0];
        i.productBatch = { name: n.product.name, productId: n.productId, warehouseId: n.warehouseId, batchNumber: angular.isDefined(t) ? n.batches[t].batchNumber : r.batchNumber, expiredDate: angular.isDefined(t) ? n.batches[t].expiredDate : r.expiredDate, price: n.product.valuationType === 1 && angular.isDefined(t) ? n.batches[t].price : n.price, count: angular.isDefined(t) ? n.batches[t].count : n.count, unit: n.product.unit, code: n.product.code, specification: n.product.specification, unpackCount: 1 };
        i.currentInventoryItem = n;
        i.productBatch.copyAmount = n.amount;
        i.productBatch.amount = i.productBatch.unpackCount * i.productBatch.price > i.productBatch.copyAmount ? i.productBatch.copyAmount : i.productBatch.unpackCount * i.productBatch.price;
        i.productBatch.amount = i.productBatch.unpackCount === i.currentInventoryItem.totalCount ? i.productBatch.copyAmount : i.productBatch.unpackCount * i.productBatch.price;
        y() })() }]);
supplychainModule.directive("transferOrderItemBatchView", ["$log", "$timeout", function(n, t) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/dialogs/inventory-product-batch-dialog/transfer-order-item-batch-view.html", link: function(n, i) { var r = function(t, r) { if (r.keyCode == 13) { var u = i.find(".table-main input.input-for-key");
                        u.length == t && (n.save(), t = 0);
                        u[t].focus() } },
                u = function() { var n = i.find(".table-main input.input-for-key");
                    n && n[0].focus() };
            (function() { n.changeEnter = r;
                t(function() { Ares.centerModal(i.closest(".modal-dialog"));
                    u() }, 5) })() } } }]);
supplychainModule.controller("TransferOrderItemBatchCtrl", ["$q", "$log", "$scope", "$modalInstance", "aresConfirmDialog", "host", "aresNotification", function(n, t, i, r, u, f, e) { "use strict"; var h = function() { r.close() },
        c = function(n) { var t = parseFloat(n); return isNaN(t) ? 0 : (t = Math.round(n * 100) / 100, isNaN(t) || t < 0 ? 0 : t) },
        s = function(n) { var t = c(n.outCount),
                i;
            n.outCount = t;
            t > n.inventoryCount && (n.outCount = n.inventoryCount);
            t == n.inventoryCount ? n.amount = n.batchTotalAmount : (i = Ares.priceToFixed(n.outCount * n.price), n.amount = _.min([i, n.batchTotalAmount]));
            o() },
        o = function() { var n = 0,
                t = 0;
            angular.forEach(i.orderItem.batchs, function(i) { n += i.outCount * 1 || 0;
                t += i.amount * 1 || 0 });
            i.orderItem.outCount = n;
            i.orderItem.amount = t;
            i.orderItem.price = Ares.priceToFixed(t / n) },
        l = function() { var n = _.find(i.orderItem.batchs, function(n) { return n.outCount > n.inventoryCount }); return n ? "物品【" + i.orderItem.product.name + "】库存数不足！" : "" },
        a = function() { o(); var n = l(); if (n) { u.warn({ message: n }); return } r.close(i.orderItem) },
        v = function(n) { if ((n.keyCode === 13 || n.key === "Enter") && i.unicodeSearchKeyword.value) { var t = _.find(i.orderItem.batchs, function(n) { return n.unicode === i.unicodeSearchKeyword.value });
                t ? t.outCount === 1 ? e.info("该唯一码对应的批次已添加") : (t.outCount = 1, s(t), e.success("该唯一码批次添加成功")) : e.error("找不到该唯一码对应的批次");
                i.unicodeSearchKeyword.value = "" } };
    (function() { i.close = h;
        i.save = a;
        i.onCountChanged = s;
        i.orderItem = f.orderItem;
        i.orderItem.product && (i.orderItem.name = i.orderItem.product.name, i.orderItem.specification = i.orderItem.product.specification, i.orderItem.unit = i.orderItem.product.unit);
        i.isEditCount = f.isEditCount;
        i.isEditCount && (i.orderItem.batchs = angular.copy(f.orderItem.batches), o()); var n = i.orderItem.batchs || i.orderItem.batches;
        i.isExpireDateVisible = n.some(function(n) { return n.expiredDate });
        i.isBatchNumberVisible = n.some(function(n) { return n.batchNumber });
        i.isUnicodeVisible = n.some(function(n) { return n.unicode });
        i.onUnicodeSearch = v;
        i.unicodeSearchKeyword = { value: "" } })() }]);
supplychainModule.directive("inventorySalesOrderItemDetailView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "aresNotification", "moduleOptionProvider", "loginContext", function(n, t, i, r, u, f, e, o) { "use strict"; return { templateUrl: "/app/supplychain/dialogs/inventory-sales-order-item-detail-dialog/inventory-sales-order-item-detail-view.html", replace: !0, link: function(n, t) { var u = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 50) },
                r = function(t) { i(function() { if (t.salesCount = parseFloat(t.salesCount), !isNaN(t.salesCount)) { t.salesCount > t.inventoryProductCount && (t.salesCount = t.inventoryProductCount); var i = _.findIndex(n.salesOrderItem.details, function(n) { return n.warehouseId == t.warehouseId }),
                                r = n.salesOrderItem.details[i];
                            n.isInventoryOutCheck ? l(r, t) : c(r, t, i) } }) },
                e = function(n) { var t = n.keyCode;
                    (t < 48 || t > 57) && t != 8 && n.preventDefault() },
                s = function(n) { i(function() { n.salesCount = parseFloat(n.salesCount);
                        isNaN(n.salesCount) && (n.salesCount = 0, r(n)) }) },
                h = function(n, t) { i(function() { n.salesCount = parseFloat(n.salesCount);
                        n.salesCount = n.salesCount + t;
                        n.salesCount < 0 ? n.salesCount = 0 : r(n) }) },
                c = function(t, i, r) { if (t) i.salesCount == 0 ? n.salesOrderItem.details.splice(r, 1) : t.count = i.salesCount;
                    else { var u = { warehouseId: i.warehouseId, warehouse: { id: i.warehouseId, name: i.warehouseName }, count: i.salesCount };
                        n.salesOrderItem.id && (u.orderItemId = n.salesOrderItem.id, u.orderId = n.salesOrderItem.orderId);
                        n.salesOrderItem.details.push(u) } n.salesOrderItem.count = n.salesOrderItem.details.map(function(n) { return parseFloat(n.count) }).reduce(function(n, t) { return n + t }, 0) },
                l = function(t, i) { var u, r, e; if (t) a(t, i);
                    else { if (n.salesOrderItem.details.length > 0) { f.error("不在申请单指定库，不能出库");
                            i.salesCount = 0; return } n.salesOrderItem.count = n.productBatchList.map(function(n) { return parseFloat(n.salesCount) }).reduce(function(n, t) { return n + t });
                        u = n.warehouseSelectMsgs[0];
                        angular.extend(u, n.getCurrentSelectInfo()) } r = _.find(n.salesOrderItem.outWarehouseDetails, function(n) { return n.id == i.id });
                    r ? i.salesCount == 0 ? (e = _.findIndex(n.salesOrderItem.outWarehouseDetails, function(n) { return n.id == r.id }), n.salesOrderItem.outWarehouseDetails.splice(e, 1)) : r.salesCount = i.salesCount : n.salesOrderItem.outWarehouseDetails.push(angular.copy(i)) },
                a = function(t) { t.count = n.getSalesOrderItemDetailCount(t.warehouseId); var i = _.find(n.warehouseSelectMsgs, function(n) { return n.warehouseId == t.warehouseId });
                    angular.extend(i, n.getCurrentSelectInfo(t.warehouseId));
                    n.salesOrderItem.count = n.getSalesOrderItemSumCount() };
            (function() { n.isInventoryCostVisible = o.isInventoryCostAllowed;
                n.onChangeSalesCount = r;
                n.onListenNumber = e;
                n.onBlurNumber = s;
                n.onEditSalesCount = h;
                n.initView = u })() } } }]);
supplychainModule.controller("InventorySalesOrderItemDetailCtrl", ["$log", "$q", "$timeout", "$scope", "$modalInstance", "host", "inventorySvc", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var l = function() { u.dismiss() },
        a = function() { var n = _.find(r.warehouseSelectMsgs, function(n) { return !n.isPass });
            n ? o.error(n.warehouseName + n.currentMsg) : u.close(r.salesOrderItem) },
        v = function() { var n = t.defer(); return e.getSalesOrderProductWarehouseInfo(r.salesOrderItem.productId).then(function(t) { r.productBatchList = t.data;
                r.isInventoryOutCheck ? r.productBatchList.forEach(function(n) { n.inventoryProductCount = n.count }) : r.productBatchList = y(r.productBatchList);
                n.resolve() }), n.promise },
        y = function(n) { var t = _.groupBy(n, function(n) { return n.warehouseId }); return _.values(t).map(function(n) { var i = n.map(function(n) { return parseFloat(n.count) }).reduce(function(n, t) { return n + t }),
                    t = n[0]; return i != t.inventoryProductCount && (i = t.inventoryProductCount), { warehouseName: t.warehouseName, warehouseId: t.warehouseId, inventoryProductCount: i } }) },
        p = function() { v().then(function() { r.productBatchList || (r.productBatchList = []);
                r.salesOrderItem.details = r.salesOrderItem.details ? r.salesOrderItem.details.filter(function(n) { return n.warehouseId }) : [];
                r.salesOrderItem.outWarehouseDetails || (r.salesOrderItem.outWarehouseDetails = []);
                r.srcSalesOrderWarehouseDetails = angular.copy(r.salesOrderItem.details);
                r.srcSalesOrderItemCount = r.salesOrderItem.count;
                r.isInventoryOutCheck && r.srcSalesOrderWarehouseDetails && r.srcSalesOrderWarehouseDetails.length > 0 && (r.productBatchList = r.productBatchList.filter(function(n) { return r.srcSalesOrderWarehouseDetails.some(function(t) { return n.warehouseId == t.warehouseId }) }));
                r.productBatchList.forEach(function(n) { var t, i;
                    r.isInventoryOutCheck ? r.salesOrderItem.outWarehouseDetails && r.salesOrderItem.outWarehouseDetails.length > 0 ? (i = _.find(r.salesOrderItem.outWarehouseDetails, function(t) { return t.id == n.id }), n.salesCount = i ? i.salesCount : 0) : n.salesCount = 0 : (t = _.find(r.salesOrderItem.details, function(t) { return t.warehouseId == n.warehouseId }), n.salesCount = t ? t.count : 0) });
                r.isInventoryOutCheck && (r.salesOrderItem.count = c(), w());
                r.initView() }) },
        w = function() { if (r.warehouseSelectMsgs = [], r.salesOrderItem.details && r.salesOrderItem.details.length > 0) r.salesOrderItem.details.forEach(function(n) { var t = { warehouseName: n.warehouse.name, warehouseId: n.warehouseId, salesCount: n.count };
                n.count = h(n.warehouseId);
                angular.extend(t, s(n.warehouseId));
                r.warehouseSelectMsgs.push(t) });
            else { var n = { warehouseName: "", warehouseId: 0, salesCount: r.srcSalesOrderItemCount };
                angular.extend(n, s());
                r.warehouseSelectMsgs.push(n) } },
        s = function(n) { var t = 0,
                i = 0,
                e, o, f, u, s, h; return r.srcSalesOrderWarehouseDetails && r.srcSalesOrderWarehouseDetails.length > 0 ? (e = _.find(r.srcSalesOrderWarehouseDetails, function(t) { return t.warehouseId == n }), o = _.find(r.salesOrderItem.details, function(t) { return t.warehouseId == n }), t = e.count, i = o.count) : (t = r.srcSalesOrderItemCount, i = r.salesOrderItem.count), f = !1, u = "", t && (i > t ? (s = i - t, u = "超过出库数量" + s + r.salesOrderItem.unit) : i < t ? (h = t - i, u = "还需出库" + h + r.salesOrderItem.unit) : (f = !0, u = "已满足需求")), { isPass: f, currentMsg: u } },
        h = function(n) { var t = r.productBatchList.filter(function(t) { return t.warehouseId == n }); return t.map(function(n) { return parseFloat(n.salesCount) }).reduce(function(n, t) { return n + t }) },
        c = function() { return r.productBatchList.map(function(n) { return parseFloat(n.salesCount) }).reduce(function(n, t) { return n + t }) };
    (function() { r.isInventoryOutCheck = f.actionType == "inventoryOut";
        r.getCurrentSelectInfo = s;
        r.getSalesOrderItemSumCount = c;
        r.getSalesOrderItemDetailCount = h;
        r.clean = l;
        r.save = a;
        r.salesOrderItem = f.salesOrderItem;
        p() })() }]);
supplychainModule.directive("inventoryTakeOrderOutAmountView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "aresNotification", "moduleOptionProvider", "loginContext", function(n, t, i, r, u, f, e, o) { return { replace: !0, templateUrl: "/app/supplychain/dialogs/inventory-take-order-out-amount-dialog/inventory-take-order-out-amount-view.html", link: function(n, t) { var f = function(n) { i(function() {
                        (n.takeCount = parseFloat(n.takeCount), isNaN(n.takeCount)) || n.takeCount > n.inventoryProductCount && (n.takeCount = n.inventoryProductCount) }) },
                a = function(t, i) { var r = _.find(n.takeOrderItem.outWarehouseDetails, function(n) { return n.id === i.id }),
                        u;
                    r ? i.takeCount === 0 ? (u = _.findIndex(n.takeOrderItem.outWarehouseDetails, function(n) { return n.id === r.id }), n.takeOrderItem.outWarehouseDetails.splice(u, 1)) : r.takeCount = i.takeCount : n.takeOrderItem.outWarehouseDetails.push(angular.copy(i)) },
                e = function() { t.find("input:first").focus() },
                s = function(t, i) { r(t, i);
                    n.getWarehouseMsgs() },
                r = function(n, t) { t ? n.takeCount = isNaN(n.takeCount) ? 0 : n.takeCount > n.inventoryProductCount ? n.inventoryProductCount : parseInt(n.takeCount) : n.count = isNaN(n.count) ? 0 : n.count > n.sumCount ? n.sumCount : parseInt(n.count) },
                h = function(t, i) { event.preventDefault();
                    r(t, i);
                    i ? t.takeCount > 0 && (t.takeCount = parseInt(t.takeCount) - 1) : t.count > 0 && (t.count = parseInt(t.count) - 1);
                    n.getWarehouseMsgs() },
                c = function(t, i) { event.preventDefault();
                    r(t, i);
                    i ? t.takeCount < t.inventoryProductCount && (t.takeCount = parseInt(t.takeCount) + 1) : t.count < t.sumCount && (t.count = parseInt(t.count) + 1);
                    n.getWarehouseMsgs() },
                l = function(t, i, u) { var e, o, f;
                    r(t, u);
                    e = window.event ? i.keyCode : i.which;
                    e === 13 && (o = angular.element(i.currentTarget).parents(".inventory-take-order-item-amount-modal-row"), f = o.next(".inventory-take-order-item-amount-modal-row"), f.length > 0 ? f.find("input").focus() : n.save()) },
                u = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog"));
                        e() }, 50) };
            (function() { n.isInventoryCostVisible = o.isInventoryCostAllowed;
                n.onChangeTakeCount = f;
                n.initView = u;
                n.onAmountChanged = s;
                n.reduceNum = h;
                n.plusNum = c;
                n.onKeyUp = l;
                u() })() } } }]);
supplychainModule.controller("InventoryTakeOrderOutAmountCtrl", ["$log", "$q", "$sce", "$timeout", "$scope", "$modalInstance", "host", "inventorySvc", "aresNotification", function(n, t, i, r, u, f, e, o, s) { "use strict"; var l = function() { f.dismiss() },
        a = function() { var n = _.find(u.warehouseMsgs, function(n) { return !n.valid }),
                t; if (n) { s.error((n.warehouseName || "") + n.msg); return } t = 0;
            u.takeOrderItem.outWarehouseDetails = [];
            _.each(u.productBatchList, function(n) { n.takeCount > 0 && (t += n.takeCount, u.takeOrderItem.outWarehouseDetails.push(angular.copy(n))) });
            u.takeOrderItem.count = t;
            f.close(u.takeOrderItem) },
        v = function() { var n = t.defer(); return o.getTakeOrderProductWarehouseInfo(u.takeOrderItem.productId).then(function(t) { u.productBatchList = t.data;
                u.productBatchList.forEach(function(n) { n.inventoryProductCount = n.count;
                    n.takeCount = 0 });
                n.resolve(!0) }), n.promise },
        y = function() { v().then(function() { u.productBatchList || (u.productBatchList = []);
                u.takeOrderItem.details = u.takeOrderItem.details ? u.takeOrderItem.details.filter(function(n) { return n.warehouseId }) : [];
                u.takeOrderItem.outWarehouseDetails || (u.takeOrderItem.outWarehouseDetails = []);
                u.srcTakeOrderWarehouseDetails = angular.copy(u.takeOrderItem.details);
                u.srcTakeOrderItemCount = u.takeOrderItem.count;
                u.productBatchList.forEach(function(n) { var t = _.find(u.takeOrderItem.outWarehouseDetails, function(t) { return t.warehouseId === n.warehouseId && t.batchNumber === n.batchNumber && t.expiredDate === n.expiredDate });
                    n.takeCount = t ? t.takeCount : 0 });
                u.initView();
                c() }) },
        h = function() { return u.productBatchList ? u.productBatchList.map(function(n) { return parseFloat(n.takeCount) }).reduce(function(n, t) { return n + t }, 0) : 0 },
        p = function(n) { var t = u.productBatchList.filter(function(t) { return t.warehouseId === n }); return t.map(function(n) { return parseFloat(n.takeCount) }).reduce(function(n, t) { return n + t }, 0) },
        c = function() { var e = [],
                t, o, r, f, n;
            u.isNeedSetWarehouseDetail && u.takeOrderItem.details.length > 0 ? (t = [], o = [], _.each(u.productBatchList, function(n) { t.indexOf(n.warehouseId) < 0 && (t.push(n.warehouseId), o.push(n)) }), _.each(t, function(n, t) { var c = o[t],
                    s, h, l = _.find(u.takeOrderItem.details, function(n) { return n.warehouseId === c.warehouseId }),
                    r, f;
                l && (r = l.count, f = p(c.warehouseId), f === r && (s = "已满足需求", h = !0), f < r && (s = '还需出库数量 <span class="error-msg-number">' + (r - f) + "<\/span> " + u.takeOrderItem.product.unit, h = !1), f > r && (s = '超过出库数量 <span class="error-msg-number">' + (f - r) + "<\/span> " + u.takeOrderItem.product.unit, h = !1), e.push({ msg: i.trustAsHtml(s), valid: h, warehouseName: c.warehouseName, neededCount: r })) })) : (n = h(), n === u.takeOrderItem.count && (r = "已满足需求", f = !0), n < u.takeOrderItem.count && (r = '还需出库数量 <span class="error-msg-number">' + (u.takeOrderItem.count - n) + "<\/span> " + u.takeOrderItem.product.unit, f = !1), n > u.takeOrderItem.count && (r = '超过出库数量 <span class="error-msg-number">' + (n - u.takeOrderItem.count) + "<\/span> " + u.takeOrderItem.product.unit, f = !1), e.push({ msg: i.trustAsHtml(r), valid: f }));
            u.warehouseMsgs = e };
    (function() { u.getTakeOrderItemSumCount = h;
        u.clean = l;
        u.save = a;
        u.takeOrderItem = e.takeOrderItem;
        u.getWarehouseMsgs = c;
        u.isNeedSetWarehouseDetail = e.isNeedSetWarehouseDetail;
        y() })() }]);
supplychainModule.directive("inventoryTakeOrderWorkflowView", ["$log", "$q", "$timeout", "eventAggregator", function(n, t, i, r) { return { replace: !0, templateUrl: "/app/supplychain/dialogs/inventory-take-order-workflow-dialog/inventory-take-order-workflow-view.html", link: function(n, t) { var f = function() { var i = t.find(".inventory-take-order-workflow-table");
                    n.takeOrder.notes ? i.css("maxHeight", "350px") : i.css("maxHeight", "380px");
                    i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } });
                    u() },
                u = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 100, !1) },
                e = function() { u();
                    t.find(".take-order-reject-reason").tooltip() },
                o = function(n, t) { var i = n.id;
                    r.publish(r.events.ProductSelected, i, t.delegateTarget) };
            (function() { n.initView = e;
                n.initTableView = f;
                n.onSelectProduct = o })() } } }]);
supplychainModule.controller("InventoryTakeOrderWorkflowCtrl", ["$log", "$q", "$timeout", "$scope", "$modalInstance", "host", "enums", "inventorySvc", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function() { u.dismiss() },
        h = function() { var n = t.defer(); return o.getTakeOrder(r.inventoryTakeOrderId).success(function(t) { r.takeOrder = t;
                n.resolve() }), n.promise },
        c = function() { var n = t.defer(); return Ares.specificOfficeUtil.enter(r.workflowItem.officeId), h().then(function() { Ares.specificOfficeUtil.exit();
                n.resolve() }), n.promise };
    (function() { r.workflowItem = f.workflowItem;
        r.workflowOfficeId = r.workflowItem.officeId;
        r.inventoryTakeOrderId = r.workflowItem.referenceId;
        r.InventoryApplicationStatus = e.InventoryApplicationStatus;
        r.clean = s;
        c().then(function() { i(function() { r.initView() }) }) })() }]);
supplychainModule.directive("inventoryTransferOrderEditView", ["$log", "$q", "$window", "$rootScope", "eventAggregator", "$timeout", "$modal", "practiceSvc", "dataDicSvc", "enums", "warehouseUtil", "numberUtil", "aresConfirmDialog", "multiOfficeDataDic", "inventoryUtil", "aresTreeViewUtil", "loginContext", "warehouseSvc", "tenantOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k) { "use strict"; return { templateUrl: "/app/supplychain/dialogs/inventory-transfer-order-edit-dialog/inventory-transfer-order-edit-view.html", replace: !0, link: function(n, r) { var tt, it = 220,
                ot = function() { tt = r.find("#productItemSearch").kendoAutoComplete({ filter: "contains", placeholder: "物品名称/拼首码/品牌/规格/内部编码/条形码/厂商编码", minLength: 1, dataTextField: "name", dataValueField: "id", headerTemplate: '<div class="dropdown-select-head" style="border-width: 0 0 1px 0;text-transform: uppercase;background-color:#f4f4f4;border-bottom: 1px solid #D6D9DF;" ><span style="display: inline-block;width:182px;margin-left:15px;">项目名称<\/span><span style="display: inline-block;width:142px;margin-left:15px;">品牌<\/span><span style="display: inline-block;width:142px;margin-left:15px;">规格名称<\/span><span style="display: inline-block;width:82px;text-align:center;">单位<\/span><\/div>', template: '<span class="dropdown-select-text" style="width:182px;margin-left:15px;" title="#: data.product.name #">#: data.product.name #<\/span><span class="dropdown-select-text" style="width:142px;margin-left:15px;">#: data.product.producer ==null ? "" :data.product.producer #<\/span><span class="dropdown-select-text" style="width:142px;margin-left:15px;">#: data.product.specification ==null ? "" :data.product.specification #<\/span><span class="dropdown-select-text" style="width:82px;margin-left:15px;text-align:center;">#: data.product.unit ==null ? "" :data.product.unit #<\/span>', dataSource: { type: "odata", serverFiltering: !0, transport: { read: function(t) { var i = t.data.filter !== undefined ? t.data.filter.filters[0] : undefined,
                                        r = i ? i.value : "";
                                    _.defer(function() { n.loadProducts(r).then(function(n) { var i = n.data ? n.data.page.items : "";
                                            t.success(i) }) }) } } }, height: it, select: function(t) { n.selectedIndex = t.item.index() }, change: function() { var t = null,
                                i = this.value();
                            this.selectedIndex = n.selectedIndex >= 0 ? n.selectedIndex : -2;
                            this.selectedIndex >= 0 ? (t = this.dataItem(this.selectedIndex), n.selectedIndex = -2) : i && i.length > 0 && (t = rt(n.products, i), t || n.loadProducts(i).then(function(n) { var r = n.data ? n.data.page.items : "",
                                    t = rt(r, i); if (t) { nt(this, t); return } }));
                            t && nt(this, t);
                            this.value("") } }).data("kendoAutoComplete") },
                rt = function(n, t) { var i = _.filter(n, function(n) { return n.producerBarCode == t || n.code == t }); return i.length == 1 ? i[0] : null },
                st = function() { tt.search("") },
                ut = function() { r.find("#receiver-drop").kendoDropDownList({ dataSource: n.toProviders, dataValueField: "id", dataTextField: "name", filter: "contains", value: n.currentInventoryTransferOrder.receiverId, select: function(t) { var i = this.dataItem(t.item.index());
                            n.currentInventoryTransferOrder.receiverId = i.id } }) },
                ht = function() { var i = t.defer(); return s.currentOfficeWorkProviderDic.load().then(function(t) { t.splice(0, 0, { id: 0, name: "请选择" });
                        n.providers = t;
                        r.find("#transferer-drop").kendoDropDownList({ dataSource: n.providers, dataValueField: "id", dataTextField: "name", filter: "contains", value: n.currentInventoryTransferOrder.transfererId, select: function(t) { var i = this.dataItem(t.item.index());
                                n.currentInventoryTransferOrder.transfererId = i.id } });
                        n.isAcrossOfficeInventoryTransferEnabled && n.currentInventoryTransferOrder.toOfficeId ? v.loadDic(n.currentInventoryTransferOrder.toOfficeId, "currentOfficeWorkProviderDic").then(function(t) { t.splice(0, 0, { id: 0, name: "请选择" });
                            n.toProviders = t || [];
                            f(function() { if (n.procurementApply) { var t = n.procurementApply.applicantId;
                                    t > 0 && (n.currentInventoryTransferOrder.receiverId = t) } ut() });
                            i.resolve(!0) }) : (n.toProviders = angular.copy(n.providers), ut(), i.resolve(!0)) }), i.promise },
                li = function() { var i = t.defer(); return n.operatories ? i.resolve(n.operatories) : s.operatoryDic.load().then(function(t) { t = _.sortBy(t, "id");
                        t.splice(0, 0, { description: "请选择" });
                        n.operatories = t;
                        i.resolve(t) }), i.promise },
                ai = function() { var i = t.defer(); return n.departments ? i.resolve(n.departments) : o.getDepartment().success(function(t) { t.splice(0, 0, { itemName: "请选择" });
                        n.departments = t;
                        i.resolve(t) }), i.promise },
                ct = function() { var i = t.defer(); return t.all([s.warehouseDic.loadActive(), b.searchWarehouses({ withOutOwner: !0 })]).then(function(t) { n.warehouses = c.filterWarehouses(t[0]);
                        n.allWarehouses = c.filterWarehouses(t[1].data);
                        i.resolve(!0) }), i.promise },
                lt = function() { var i = t.defer(); return n.isAcrossOfficeInventoryTransferEnabled && n.currentInventoryTransferOrder.toOfficeId ? b.searchWarehouses({ officeIds: [n.currentInventoryTransferOrder.toOfficeId], withOutOwner: !0 }).success(function(t) { t && (t = t.filter(function(n) { return !n.isInactive }));
                        n.toWarehouses = t || [];
                        i.resolve(!0) }) : (n.toWarehouses = angular.copy(n.allWarehouses), i.resolve(!0)), i.promise },
                at = function() { var t = r.find("#toWarehouse").data("kendoDropDownList"),
                        i, u;
                    t && n.toWarehouses.length > 0 && (t.dataSource.data(n.toWarehouses), i = _.find(n.toWarehouses, { isDefault: !0 }), u = i ? i.id : n.toWarehouses && n.toWarehouses.length > 0 ? n.toWarehouses[0].id : 0, t.value(u), n.currentInventoryTransferOrder.toWarehouseId = u) },
                vt = function() { var t = r.find("#receiver-drop").data("kendoDropDownList"),
                        i, u;
                    t && (t.dataSource.data(n.toProviders), i = _.find(n.toProviders, { id: n.currentInventoryTransferOrder.receiverId }), u = i ? i.id : n.toProviders && n.toProviders.length > 0 ? n.toProviders[0].id : 0, t.value(u), n.currentInventoryTransferOrder.receiverId = u) },
                yt = function() { var u = n.getCurrentWarehouseId(),
                        t, i;
                    r.find("#fromWarehouse").kendoDropDownList({ dataTextField: "name", dataValueField: "id", value: u, dataSource: n.warehouses, select: function(t) { var u = t.item.context.innerText,
                                i = _.find(n.warehouses, { name: u }).id,
                                r = $("#fromWarehouse").data("kendoDropDownList"); if (n.isFromProcurementApply) { n.currentInventoryTransferOrder.items = [];
                                f(function() { n.addProductsFromProcurementApply() });
                                r.value(i);
                                d(i); return } n.currentInventoryTransferOrder && n.currentInventoryTransferOrder.items && n.currentInventoryTransferOrder.items.length > 0 && (t.preventDefault(), a.confirm({ message: "切换调拨仓库将清空调拨物品列表" }).then(function() { n.currentInventoryTransferOrder.items = [];
                                r.value(i);
                                d(i) })) }, change: function(n) { var t = n.sender.value();
                            d(t) } });
                    t = _.find(n.toWarehouses, { isDefault: !0 });
                    i = t ? t.id : n.toWarehouses && n.toWarehouses.length > 0 ? n.toWarehouses[0].id : 0;
                    r.find("#toWarehouse").kendoDropDownList({ dataSource: n.toWarehouses, dataTextField: "name", dataValueField: "id", value: n.currentInventoryTransferOrder.toWarehouseId || i, select: function(t) { n.currentInventoryTransferOrder.toWarehouseId = this.dataItem(t.item)[this.options.dataValueField] || null;
                            n.refreshTotalAmount() } }) },
                d = function(t) { n.currentInventoryTransferOrder.fromWarehouseId = t * 1;
                    n.rightHasSpu == 1 && l() },
                pt = function() { y.getProductCategories().then(function(t) { n.selCategoryId = 0;
                        n.selCategory = { name: "全部分类", id: 0 };
                        n.categoriesTree = p.unflatten(t, "showOrder");
                        n.categoriesTree.splice(0, 0, n.selCategory) }) },
                g = function(t, i) { var r = y.formatNumber(n.currentInventoryTransferOrder.items[i].outCount, !0);
                    n.currentInventoryTransferOrder.items[i].outCount = r > n.currentInventoryTransferOrder.items[i].inventoryCount ? n.currentInventoryTransferOrder.items[i].inventoryCount : r;
                    n.refreshTotalAmount() },
                wt = function(n, t) { n.outCount > 0 && (n.outCount -= 1, g("", t), event.preventDefault()) },
                bt = function(n, t) { n.outCount += 1;
                    g("", t);
                    event.preventDefault() },
                nt = function(t, i, r, u) { f(function() { var f, o, s, e; if (!r && (f = angular.copy(i), f != null)) { if (o = _.find(n.currentInventoryTransferOrder.items, function(n) { return n.product.id == f.product.id }), o) { a.warn({ message: "此物品已经在调拨物品列表中！" }); return } t && t.value("");
                            n.currentInventoryTransferOrder.items || (n.currentInventoryTransferOrder.items = []);
                            s = { productId: f.product.id, fromWarehouseId: n.currentInventoryTransferOrder.fromWarehouseId };
                            e = 0;
                            angular.forEach(f.batches, function(n) { n.id = 0;
                                n.batchTotalAmount = n.amount;
                                n.inventoryCount = n.count;
                                n.amount = 0;
                                e += n.count });
                            f.isSingleBatche = f.batches.length == 1;
                            f.outCount = f.applyCount ? f.isSingleBatche ? f.applyCount >= e ? e : f.applyCount : 0 : f.isSingleBatche ? 1 : 0;
                            f.inventoryCount = e;
                            f.amount = 0;
                            n.currentInventoryTransferOrder.items.splice(0, 0, f);
                            n.checkOutOrderItemExist();
                            u || n.refreshTotalAmount();
                            n.currentInventoryTransferOrder.items[0].isSingleBatche || n.isFromProcurementApply || et(n.currentInventoryTransferOrder.items[0]) } }) },
                kt = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && l() },
                dt = function() { var t = n.currentInventoryTransferOrder.id ? "编辑调拨单" : "新建调拨单";
                    n.slideModalTitle = t },
                gt = function() { r.find(".spu-list .spu-list-content").mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 }, mouseWheel: { preventDefault: !0 }, callbacks: { whileScrolling: function(t) { t.topPct >= 90 && l(n.pageIndex) } } }) },
                l = function(t) { var i = r.find(".spu-list .spu-list-content"),
                        u = function(r) { n.isSearching = !1;
                            n.productList = r;
                            n.groupSkuToSpu(r);
                            f(function() { i.mCustomScrollbar("update");
                                t || i.mCustomScrollbar("scrollTo", "top") }) };
                    n.isSearching || (n.isSearching = !0, t ? n.searchProductList(n.selCategoryId, n.searchName, t).then(u) : (n.productList = [], n.productUnityList = [], f(function() { i.mCustomScrollbar("update");
                        n.searchProductList(n.selCategoryId, n.searchName, t).then(u) }))) },
                ni = function() { gt();
                    l() },
                ti = function(n, t) { var i = n.productId || n.id;
                    u.publish(u.events.ProductSelected, i, t.delegateTarget);
                    Ares.retainOnePopover() },
                ii = function(t) { n.rightHasSpu = 1;
                    ft(t);
                    ni() },
                ft = function(n) { var t = angular.element(".inventory-slide").parent(".modal-content").parent(".modal-dialog");
                    n == 1 ? t.addClass("full-screen") : t.removeClass("full-screen") },
                et = function(t) { var i = e.open({ animation: !0, backdrop: "static", template: "<transfer-order-item-batch-view><\/transfer-order-item-batch-view>", controller: "TransferOrderItemBatchCtrl", windowClass: "ares-medium-modal-content product-batch-wider", resolve: { host: function() { return { orderItem: angular.copy(t), isEditCount: 1 } } } });
                    i.result.then(function(i) { i && (t.batches = i.batchs, t.outCount = i.outCount, n.refreshTotalAmount());
                        r.find("#productItemSearch").focus() }) },
                ri = function() { var t = n.currentInventoryTransferOrder.inOrderAction != h.InOrderAction.PurchaseIn && (n.currentInventoryTransferOrder.state == 0 || !n.currentInventoryTransferOrder.id);
                    n.canDisableProductSearch = !t },
                ui = function() { var t = angular.element(i).height(),
                        u = n.isAcrossOfficeInventoryTransferEnabled ? 400 : 390,
                        o = n.isAcrossOfficeInventoryTransferEnabled ? 80 : 90,
                        s = t - u - o,
                        f;
                    it = t - u;
                    f = r.find(".table-main .table-main-content");
                    f.height(s); var h = r.find(".slide-modal-right"),
                        c = r.find(".spu-list-content"),
                        e = 70,
                        l = t - e,
                        a = t - e - 100;
                    h.height(l);
                    c.height(a) },
                fi = function(t, i) { var u = r.find(".table-main input.input-for-key");
                    n.keypressCode == 13 && (t === 0 ? u.each(function(n) { n == 0 && angular.element(this).focus() }) : t == 1 && r.find(".productItemSearch input").focus());
                    i.stopPropagation() },
                ei = function() { var u = r.find("#transferer-drop").data("kendoDropDownList"),
                        t, i;
                    u && (n.currentInventoryTransferOrder.transfererId = u.value());
                    t = r.find("#receiver-drop").data("kendoDropDownList");
                    t && (n.currentInventoryTransferOrder.receiverId = t.value());
                    i = r.find("#orderDateInput").data("kendoDatePicker");
                    i && (n.currentInventoryTransferOrder.orderDate = moment(i.value()).format("YYYY-MM-DD")) },
                oi = function(t) { n.selCategory = t;
                    n.selCategoryId = t ? t.id : 0;
                    n.selCategoriesIds = y.getAllSubCategoriesIds(t);
                    l() },
                si = function(t) { var i = t.sender.value();
                    i == 0 ? (n.toWarehouses = angular.copy(n.warehouses), n.toProviders = angular.copy(n.providers)) : (n.toWarehouses = [{ id: 0, name: "请选择" }], n.toProviders = [{ id: 0, name: "请选择" }]);
                    n.selectedOfficeIdsArray = [];
                    n.currentInventoryTransferOrder.toWarehouseId = 0;
                    n.currentInventoryTransferOrder.receiverId = 0;
                    n.setToWarehouseDropDownDataSource();
                    n.setToProviderDropDownDataSource();
                    n.currentInventoryTransferOrder.toOfficeId = null },
                hi = function() { var n = [ht(), lt()]; return t.all(n).then(function() { return yt(), ot(), dt(), ri(), !0 }) },
                ci = function() { y.getProductCodeOptions().then(function(t) { n.productCodeOptions = t }) };
            (function() { n.showBatchItemDialog = et;
                n.addProductToList = nt;
                n.onEnter = kt;
                n.onSelectedProduct = ti;
                n.onSearchProductUnity = l;
                n.leftSwitch = ii;
                n.onCountChanged = g;
                n.changeEnter = fi;
                n.halfFullScreen = ft;
                n.reduceNum = wt;
                n.plusNum = bt;
                n.focusAutocomplete = st;
                n.setSaveData = ei;
                n.onProductCategoryChange = oi;
                n.setToWarehouseDropDownDataSource = at;
                n.setToProviderDropDownDataSource = vt;
                n.onChangeTransferType = si;
                ui();
                k.getTenantOption("IsAcrossOfficeInventoryTransferEnabled").then(function(t) { n.isAcrossOfficeInventoryTransferEnabled = t;
                    ct().then(function() { var t = w.providerId;
                        n.init(t).then(function() { hi().then(function() { n.isFromProcurementApply && (n.currentInventoryTransferOrder.toWarehouseId = n.toWarehouses && n.toWarehouses.length > 0 ? n.toWarehouses[0].id : 0, n.addProductsFromProcurementApply()) }) }) }) });
                pt();
                ci() })() } } }]);
supplychainModule.controller("InventoryTransferOrderEditCtrl", ["$log", "$scope", "$rootScope", "$modalInstance", "$q", "$modal", "$document", "officeOptionSvc", "aresNotification", "enums", "inventoryProductSvc", "productSvc", "aresConfirmDialog", "inventorySvc", "host", "eventAggregator", "inventoryInOrderUtil", "$timeout", "warehouseUtil", "loginContext", "inventoryUtil", "officeSvc", "officeSelectorUtil", "moduleOptionProvider", "multiOfficeDataDic", "warehouseSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt, ut) { "use strict"; var vt = function() { r.dismiss();
            t.offKeyDown() },
        yt = function(n) { t.currentInventoryTransferOrder && t.currentInventoryTransferOrder.items && (n < 0 || n > t.currentInventoryTransferOrder.items.length || (t.currentInventoryTransferOrder.items.splice(n, 1), ft(), t.checkOutOrderItemExist())) },
        st = function() { var n, i, r; return t.currentInventoryTransferOrder.toOfficeId == d.officeId ? "跨机构调拨收入单位不能是当前机构！" : t.currentInventoryTransferOrder.orderType == 1 && !t.currentInventoryTransferOrder.toOfficeId ? "请选择收入单位！" : t.currentInventoryTransferOrder.items && t.currentInventoryTransferOrder.items.length > 0 ? (n = _.find(t.currentInventoryTransferOrder.items, function(n) { return n.outCount == 0 || n.outCount == null }), n) ? (i = n.product.name, r = "物品【" + i + "】数量必须大于0！", r) : (n = _.find(t.currentInventoryTransferOrder.items, function(n) { return n.outCount > n.count }), n) ? (i = n.product.name, r = "物品【" + i + "】库存数不足！", r) : t.currentInventoryTransferOrder.fromWarehouseId <= 0 ? "请选择调出仓库 ！" : t.currentInventoryTransferOrder.toWarehouseId <= 0 ? "请选择调入仓库 ！" : t.currentInventoryTransferOrder.fromWarehouseId == t.currentInventoryTransferOrder.toWarehouseId ? "调出仓库与调入仓库不能相同 ！" : (t.setSaveData(), !g.checkOrderDateValid(t.currentInventoryTransferOrder.orderDate)) ? "请输入单据日期 ！" : g.checkOrderGreaterThanToday(t.currentInventoryTransferOrder.orderDate) ? "单据日期不能大于当前日期 ！" : t.currentInventoryTransferOrder.transfererId <= 0 ? "请选择发货人 ！" : t.currentInventoryTransferOrder.receiverId <= 0 ? "请选择收货人！" : t.currentInventoryTransferOrder.transfererId == t.currentInventoryTransferOrder.receiverId <= 0 ? "发货人与收货人不能相同！" : "" : "请添加调拨物品!" },
        ht = function() { var i = t.currentInventoryTransferOrder.transfererId > 0 ? t.currentInventoryTransferOrder.transfererId : null,
                r = t.currentInventoryTransferOrder.receiverId > 0 ? t.currentInventoryTransferOrder.receiverId : null,
                n = { id: t.currentInventoryTransferOrder.id, fromWarehouseId: t.currentInventoryTransferOrder.fromWarehouseId, toWarehouseId: t.currentInventoryTransferOrder.toWarehouseId, orderNumber: t.currentInventoryTransferOrder.orderNumber, orderDate: t.currentInventoryTransferOrder.orderDate, notes: t.currentInventoryTransferOrder.notes, state: t.currentInventoryTransferOrder.state, transfererId: i, receiverId: r, orderType: t.currentInventoryTransferOrder.orderType, toOfficeId: t.currentInventoryTransferOrder.toOfficeId, items: pt() }; return t.isFromProcurementApply && (n.procurementApplyOrderId = t.procurementApply.id), n },
        pt = function() { var n = []; return angular.forEach(t.currentInventoryTransferOrder.items, function(i) { angular.forEach(i.batches, function(r) { i.batches.length == 1 && (r.outCount = i.outCount);
                    n.push({ id: r.id, name: i.product.name, productId: i.product.id, batchNumber: r.batchNumber, expiredDate: r.expiredDate, count: r.outCount, price: r.price, notes: i.notes, code: i.product.code, unit: i.product.unit, producer: i.product.producer, state: t.currentInventoryTransferOrder.state, specification: i.product.specification }) }) }), n },
        ct = function() { var n = ht(),
                i = u.defer(),
                r = st(); return r ? (a.warn({ message: r }), i.reject()) : (ft(), t.currentInventoryTransferOrder.orderDate || (t.currentInventoryTransferOrder.orderDate = moment(Ares.today()).format("YYYY-MM-DD")), n = ht(), n.id == -1 || n.id == null || n.id == 0 ? v.addTransferOrder(n).success(function(n) { t.currentInventoryTransferOrder.id = n.id;
                i.resolve(!0) }).error(function(n) { g.showInventoryErrorMessage(n, "保存失败");
                i.reject() }) : v.updateTransferOrder(n).success(function() { i.resolve(!0) }).error(function(n) { g.showInventoryErrorMessage(n, "保存失败");
                i.reject() })), i.promise },
        ft = function() { fi(_.pluck(t.currentInventoryTransferOrder.items, "productId")).then(function(n) { var i = 0,
                    r = 0;
                angular.forEach(t.currentInventoryTransferOrder.items, function(t) { var u = t.outCount * 1 || 0,
                        f, e, o;
                    t.product.valuationType == 1 && t.batches.length > 1 ? (f = 0, t.count = 0, angular.forEach(t.batches, function(n) { var i = n.outCount * 1 || 0;
                        i > 0 && (f += n.amount, t.count += n.count) }), t.amount = f, t.price = u == 0 ? 0 : et(f / u)) : (e = et(t.price * u), u == t.count ? t.amount = t.batches[0].batchTotalAmount : (e = et(t.price * u), t.amount = _.min([e, t.batches[0].batchTotalAmount])));
                    i += t.amount;
                    r += u;
                    o = n[t.productId];
                    t.inInventoryCount = o ? o : 0 });
                t.currentInventoryTransferOrder.amount = et(i);
                t.currentInventoryTransferOrder.count = r }) },
        wt = function() { r.dismiss("close") },
        et = function(n) { return Ares.priceToFixed(n) },
        bt = function() { Ares.ensureNotDuplicated("SaveInventoryTransferOrder") && ct().then(function() { t.currentInventoryTransferOrder.state == 0 && (p.publish(p.events.RefreshIventoryHint, null, "InventoryTransferOrderEditCtrl"), p.publish(p.events.IventoryTransferOrderCreated, t.currentInventoryTransferOrder, "InventoryCheckEditCtrl"));
                s.success("保存成功");
                t.offKeyDown();
                r.close(t.currentInventoryTransferOrder) }) },
        kt = function() { if (Ares.ensureNotDuplicated("SaveAndExecuteInventoryTransferOrder")) { var n = st(); if (n) { a.warn({ message: n }); return } t.currentInventoryTransferOrder.orderType == 1 ? lt() : a.confirm({ message: "您确定执行该单据吗？单据执行后库存将发生变更" }).then(function() { lt() }) } },
        lt = function() { ct().then(function() { dt(); var n = "保存并执行";
                t.currentInventoryTransferOrder.id == -1 || t.currentInventoryTransferOrder.id == null || (n = "编辑");
                Ares.sensors.track("InventoryOperation", { OrderNumber: t.currentInventoryTransferOrder.orderNumber, OperationType: "调拨", OperationMode: n }) }) },
        dt = function() { v.approveTransferOrder(t.currentInventoryTransferOrder.id).success(function() { p.publish(p.events.RefreshIventoryHint, null, "InventoryTransferOrderEditCtrl");
                t.currentInventoryTransferOrder.state = 1;
                r.close(t.currentInventoryTransferOrder);
                s.success("调拨成功!") }).error(function(n) { n.name == "InventoryOperationException" || n.name == "NotInOrderInformationException" ? (t.isDisableSaveBtn = !1, a.warn({ message: n.message })) : (s.error("调拨失败!"), t.isDisableSaveBtn = !1) }) },
        gt = function(n) { n = n < 0 ? 0 : n; var i = u.defer(),
                f = moment(Ares.today()).format("YYYY-MM-DD"),
                r = ot(); return t.isFromProcurementApply = y.isFromProcurementApply, t.procurementApply = y.procurementApply, t.currentInventoryTransferOrder = { state: 0, amount: 0, consigneeType: -1, orderDate: f, fromWarehouseId: r, toWarehouseId: r, transfererId: n, receiverId: n, id: y.orderId || null }, t.isAcrossOfficeInventoryTransferEnabled && (t.currentInventoryTransferOrder.orderType = 0), t.isFromProcurementApply && (t.currentInventoryTransferOrder.orderType = 1, t.currentInventoryTransferOrder.toOfficeId = t.procurementApply.officeId), t.currentInventoryTransferOrder.id > 0 && t.currentInventoryTransferOrder.id != null ? ni(t.currentInventoryTransferOrder.id).then(function() { i.resolve(!0) }) : i.resolve(!0), i.promise },
        ni = function(i) { var r = u.defer(); return v.getTransferOrder(i).success(function(n) { var i; if (n) { i = { id: n.id, fromWarehouseId: n.fromWarehouseId, toWarehouseId: n.toWarehouseId, orderNumber: n.orderNumber, orderDate: n.orderDate, notes: n.notes, state: n.state, transfererId: n.transfererId, receiverId: n.receiverId, toOfficeId: n.toOfficeId, orderType: n.orderType, items: [] };
                    rt.loadDic(i.toOfficeId, "currentOfficeWorkProviderDic");
                    t.selectedOfficeIdsArray = [i.toOfficeId]; var f = angular.copy(n.items),
                        u = _.groupBy(f, "productId"),
                        e = _.keys(u);
                    angular.forEach(e, function(n) { var t = u[n],
                            r = [],
                            f = 0,
                            e = 0,
                            o;
                        angular.forEach(t, function(n) { n.outCount = n.count;
                            f += n.inventoryCount;
                            e += n.outCount;
                            r.push(n) });
                        o = { productId: n, product: { id: n, name: t[0].name, producer: t[0].producer, specification: t[0].specification, valuationType: t[0].valuationType, unit: t[0].unit }, isSingleBatche: r.length == 1, batches: r, inventoryCount: f, outCount: e, notes: t[0].notes };
                        i.items.push(o) });
                    t.currentInventoryTransferOrder = i;
                    ft();
                    r.resolve(!0) } }).error(function(t) { s.error("无法获取订单详情");
                n.log(t);
                r.reject() }), r.promise },
        ti = function(n, i, r) { var f = u.defer(),
                e = t.previousSearchCategoryId == n && t.previousSearchName == i,
                o, s; return e && r == t.pageCount ? f.resolve(t.productList) : (r = r ? r + 1 : 1, o = ot() || null, s = { warehouseId: o, count: 1, pageIndex: r, pageSize: 50, categoriesIds: t.selCategoriesIds, searchText: i }, c.searchInventoryProduct(s).success(function(u) { t.previousSearchCategoryId = n;
                t.previousSearchName = i;
                at(u.page.items); var o = u.page.items;
                e && r > t.pageIndex && (o = t.productList.concat(o));
                t.pageIndex = u.page.pageIndex;
                t.pageCount = u.page.pageCount;
                f.resolve(o) })), f.promise },
        ii = function(n) { return n.valuationType == h.InventoryValuationType.SUCM || n.product && n.product.valuationType == h.InventoryValuationType.SUCM },
        ri = function() { _.each(t.products, function(n) { var i = _.find(t.currentInventoryTransferOrder.items, function(t) { return t.product.id === n.product.id });
                n.isExist = !!i });
            _.each(t.productUnityList, function(n) { _.each(n.products, function(n) { var i = _.find(t.currentInventoryTransferOrder.items, function(t) { return t.product.id === n.product.id });
                    n.isExist = !!i }) }) },
        ot = function() { var n = null,
                r; return t.warehouses && t.warehouses.length > 0 && (n = t.warehouses[0].id || null, r = k.getDefaultWarehouse(t.warehouses), n = r ? r.id : n), n = i.currentWarehouseId > 0 ? i.currentWarehouseId : n, n = y.fromWarehouseId ? y.fromWarehouseId : n, t.currentInventoryTransferOrder && t.currentInventoryTransferOrder.fromWarehouseId ? t.currentInventoryTransferOrder.fromWarehouseId : n },
        ui = function(n) { var i = ot() || null,
                r = { warehouseId: i, pageSize: 20, count: 1, searchText: n }; return c.searchInventoryProduct(r).success(function(n) { var i = at(n.page.items); return t.products = n.page.items, i }) },
        fi = function(n) { var i = u.defer(),
                r = t.currentInventoryTransferOrder.toWarehouseId,
                f = { warehouseId: r, productIds: n }; return c.getInventoryProductsCount(f).success(function(n) { i.resolve(n) }), i.promise },
        at = function(n) { angular.forEach(n, function(n) { n.name = n.product.name;
                n.code = n.product.code;
                n.pinyin = n.product.pinyin;
                n.barCode = n.product.barCode;
                n.producerBarCode = n.product.producerBarCode;
                n.procedureCode = n.product.procedureCode;
                n.itemName = n.product.itemName }) },
        ei = function() { e.on("keydown", function(n) { t.keypressCode = n.keyCode == 13 ? 13 : 0 }) },
        oi = function() { e.off("keydown") },
        si = function() { nt.getNodesInGroup().success(function(n) { t.officeTreeData = tt.setId(n) }) },
        hi = function(n) { t.currentInventoryTransferOrder.toOfficeId = n[0].id;
            t.selectedOfficeIdsArray = [t.currentInventoryTransferOrder.toOfficeId];
            ut.searchWarehouses({ officeIds: t.selectedOfficeIdsArray, withOutOwner: !0 }).success(function(n) { n && (n = n.filter(function(n) { return !n.isInactive }));
                t.toWarehouses = n || [];
                t.setToWarehouseDropDownDataSource() });
            rt.loadDic(t.currentInventoryTransferOrder.toOfficeId, "currentOfficeWorkProviderDic").then(function(n) { t.toProviders = n || [];
                t.setToProviderDropDownDataSource() }) },
        ci = function() { ei();
            t.isAcrossOfficeInventoryTransferEnabled && si() },
        li = function(n) { t.productUnityList = t.productUnityList || [];
            _.each(n, function(n) { var i = _.find(t.productUnityList, function(t) { return t.id === n.productUnityId });
                i ? _.some(i.products, function(t) { return t.product.id === n.product.id }) || i.products.push(angular.copy(n)) : (i = { id: n.productUnityId, imgUrl: n.imgUrl, name: n.product.name, producer: n.product.producer, category: n.product.category, products: [angular.copy(n)] }, t.productUnityList.push(i)) }) },
        ai = function() { var n = {},
                i = [];
            _.each(t.procurementApply.items, function(t) { i.push(t.productId);
                n[t.productId] = _.clone(t) });
            c.searchInventoryProduct({ productIds: i, warehouseId: t.currentInventoryTransferOrder.fromWarehouseId, pageSize: i.length, pageIndex: 1 }).success(function(i) { _.each(i.page.items, function(i) { var r = n[i.productId];
                    i.applyCount = r.count - r.handledCount < 0 ? 0 : r.count - r.handledCount;
                    t.addProductToList(null, i, !1, !0);
                    delete n[i.productId] });
                _.each(n, function(n) { n.applyCount = n.count - n.handledCount < 0 ? 0 : n.count - n.handledCount;
                    n.count = 0;
                    n.product = _.clone(n);
                    n.batches = [_.clone(n)];
                    t.addProductToList(null, n, !1, !0) });
                b(function() { ft() }) }) };
    (function() { t.clean = vt;
        t.refreshTotalAmount = ft;
        t.removeOutOrderItem = yt;
        t.close = wt;
        t.priceToFixed = et;
        t.save = bt;
        t.saveAndExecute = kt;
        t.init = gt;
        t.searchProductList = ti;
        t.isProductSUCM = ii;
        t.checkOutOrderItemExist = ri;
        t.loadProducts = ui;
        t.getCurrentWarehouseId = ot;
        t.offKeyDown = oi;
        t.onOfficeSelected = hi;
        t.groupSkuToSpu = li;
        t.addProductsFromProcurementApply = ai;
        ci() })() }]);
supplychainModule.directive("procurementApplyOrderWorkflowView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "eventAggregator", function(n, t, i, r, u, f) { return { replace: !0, templateUrl: "/app/supplychain/dialogs/procurement-apply-order-workflow-dialog/procurement-apply-order-workflow-view.html", link: function(n, t) { var u = function() { var i = t.find(".procurement-apply-order-workflow-table");
                    n.procurmentApplyOrder.notes ? i.css("maxHeight", "350px") : i.css("maxHeight", "380px");
                    i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } });
                    r() },
                r = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 100) },
                e = function(n, t) { var i = n.productId || item.id;
                    f.publish(f.events.ProductSelected, i, t.delegateTarget) };
            (function() { n.initTableView = u;
                n.onSelectProduct = e;
                r() })() } } }]);
supplychainModule.controller("ProcurementApplyOrderWorkflowCtrl", ["$log", "$q", "$timeout", "$scope", "$modalInstance", "host", "enums", "procurementApplyOrderSvc", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function() { u.dismiss() },
        h = function() { var n = t.defer(); return o.getById(r.ProcurementApplyOrderId).then(function(t) { r.procurmentApplyOrder = t.data;
                r.procurmentApplyOrder.applyTimeStr = moment(t.data.applyTime).format("YYYY-MM-DD HH:mm");
                n.resolve() }), n.promise },
        c = function() { var n = t.defer(),
                u = r.workflowItem.status,
                f, i; return u == 2 || u == 3 ? (f = r.workflowItem.referenceSnapshot, i = JSON.parse(f), r.isProcessed = !0, r.procurmentApplyOrder = i, r.procurmentApplyOrder.applyTimeStr = moment(i.applyTime).format("YYYY-MM-DD HH:mm"), n.resolve()) : (Ares.specificOfficeUtil.enter(r.workflowItem.officeId), h().then(function() { Ares.specificOfficeUtil.exit();
                n.resolve() })), n.promise };
    (function() { r.workflowItem = f.workflowItem;
        r.workflowOfficeId = r.workflowItem.officeId;
        r.ProcurementApplyOrderId = r.workflowItem.referenceId;
        r.clean = s;
        c().then(function() { i(function() { r.initTableView() }) }) })() }]);
supplychainModule.directive("procurementPayOrderWorkflowView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "eventAggregator", function(n, t, i, r, u, f) { return { replace: !0, templateUrl: "/app/supplychain/dialogs/procurement-pay-order-workflow-dialog/procurement-pay-order-workflow-view.html", link: function(n, t) { var u = function() { var i = t.find(".procurement-pay-order-workflow-table");
                    n.payOrder.notes ? i.css("maxHeight", "350px") : i.css("maxHeight", "380px");
                    i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } });
                    r() },
                r = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 100) },
                e = function(n, t) { var i = n.productId || n.id;
                    f.publish(f.events.ProductSelected, i, t.delegateTarget) };
            (function() { n.onSelectProduct = e;
                n.initTableView = u;
                n.initData().then(function() { r() }) })() } } }]);
supplychainModule.controller("ProcurementPayOrderWorkflowCtrl", ["$log", "$q", "$filter", "$timeout", "$scope", "enums", "$modalInstance", "host", "procurementSvc", "inventoryProductSvc", function(n, t, i, r, u, f, e, o, s) { "use strict"; var h = function() { e.dismiss() },
        c = function() { var n = t.defer(),
                r = []; return s.getPayOrderFullById(u.procurementPayOrderId).success(function(t) { t.items = [];
                angular.forEach(t.procurementOrders, function(n) { angular.forEach(n.procurementOrderItems, function(n) { t.items.push(n);
                        r.push(n.productId) }) });
                t.statusHtml = i("procurementPayOrderStatusLabelStr")(t);
                u.payOrder = t;
                n.resolve() }), n.promise },
        l = function() { var n = t.defer(); return Ares.specificOfficeUtil.enter(u.workflowItem.officeId), c().then(function() { Ares.specificOfficeUtil.exit();
                n.resolve() }), n.promise };
    (function() { u.workflowItem = o.workflowItem;
        u.procurementPayOrderId = u.workflowItem.referenceId;
        u.workflowOfficeId = u.workflowItem.officeId;
        u.clean = h;
        u.initData = l })() }]);
supplychainModule.directive("procurementWayBillOrderView", ["$log", "$modal", "$timeout", function(n, t, i) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/dialogs/procurement-way-bill-order-dialog/procurement-way-bill-order-view.html", link: function(n, t) {
            (function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 100) })() } } }]);
supplychainModule.controller("ProcurementWayBillOrderCtrl", ["$q", "$log", "$scope", "$modalInstance", "host", function(n, t, i, r, u) { "use strict"; var f = function() { r.dismiss() };
    (function() { i.close = f;
        i.waybills = angular.copy(u.waybills);
        i.payOrderType = u.payOrderType })() }]);
supplychainModule.directive("inventoryInorderPrintTemplate", ["$log", "pictureSvc", "practiceSvc", "$filter", "$sce", "toothUtil", function() { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/inventory-print/inventory-inorder-print-template.html", link: function(n) {
            (function() { var t = new Date;
                n.totayStr = moment(t).format("YYYY-MM-DD HH:mm:ss") })() } } }]);
supplychainModule.directive("inventoryOutOrderPrintTemplate", ["$log", "pictureSvc", "practiceSvc", "$filter", "$sce", "toothUtil", function() { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/inventory-print/inventory-out-order-print-template.html", link: function() {
            (function() {})() } } }]);
supplychainModule.directive("procurementPayorderPrintTemplate", ["$log", "pictureSvc", "practiceSvc", "$filter", "$sce", "toothUtil", function() { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/inventory-print/procurement-payorder-print-template.html", link: function(n) {
            (function() { var t = new Date;
                n.totayStr = moment(t).format("YYYY-MM-DD HH:mm:ss") })() } } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r) { var u = this;
            this.$q = n;
            this.dataDicSvc = t;
            this.inventoryUtil = i;
            this.permissionProvider = r;
            this.initBasicData = function(n) { var t = [],
                    i; return n.basicData = {}, i = function(n, t) { return n.splice(0, 0, { id: 0, name: t }), n }, t.push(u.dataDicSvc.userNameDic.load().then(function(t) { t = _.filter(t, function(n) { return !n.isInactive && n.isShow != !1 });
                    n.basicData.createUsers = i(t, "全部制单人") })), t.push(u.dataDicSvc.currentOfficeWorkProviderDic.load().then(function(t) { n.basicData.operators = i(t, "全部负责人") })), t.push(u.dataDicSvc.warehouseDic.load().then(function(t) { n.basicData.warehouses = t })), t.push(u.dataDicSvc.officeDic.load().then(function(t) { n.basicData.offices = t })), t.push(u.inventoryUtil.getProductCodeOptions().then(function(t) { n.productCodeOptions = t })), u.$q.all(t) } } return n.prototype.formatOrder = function(n, t) { var e = this.permissionProvider,
                r, u, f, i;
            n.warehouseId && (r = _.find(t.basicData.warehouses, function(t) { return t.id == n.warehouseId }), r && (n.warehouseName = r.name, n.hasPermission = e.getWarehousePermission(r)));
            n.recordCreatedUser && (u = _.find(t.basicData.createUsers, function(t) { return t.id == n.recordCreatedUser }), n.createUserStr = u ? u.name : "");
            n.operatorId && (f = _.find(t.basicData.operators, function(t) { return t.id == n.checkerId }), n.checkerStr = f ? f.name : "");
            i = [];
            angular.forEach(n.items, function(n) { angular.forEach(n.details, function(t) { t.productId = n.productId;
                    t.specification = n.specification;
                    t.unit = n.unit;
                    t.producer = n.producer;
                    t.name = n.name;
                    t.code = n.code;
                    t.countGap = t.actualCount - t.inventoryCount;
                    i.push(t) }) });
            n.details = i;
            n.hasBatchNumber = _.any(i, function(n) { return n.batchNumber });
            n.hasExpiredDate = _.any(i, function(n) { return n.expiredDate });
            n.hasUnicode = _.any(i, function(n) { return n.unicode });
            n.columnState = n.hasBatchNumber && n.hasExpiredDate ? 2 : n.hasBatchNumber ? 1 : n.hasExpiredDate ? 1 : 0 }, n.$inject = ["$q", "dataDicSvc", "inventoryUtil", "permissionProvider"], n }();
    supplychainModule.factory("inventoryCheckOrderUtil", Ares.tsProvider(n)) })(inventory || (inventory = {}));
supplychainModule.factory("inventoryInOrderUtil", ["$log", "$q", "$modal", "$filter", "productSvc", "productUnitySvc", "permissionProvider", "loginContext", "enums", "inventoryUtil", "dataDicSvc", "practiceSvc", "$sce", function(n, t, i, r, u, f, e, o, s, h, c, l, a) { "use strict"; let v = r("toDeliverTypeStr"); var y = function(n, t) { var r = i.open({ animation: !0, backdrop: "static", template: "<operation-log-list-view><\/operation-log-list-view>", controller: "OperationLogListCtrl", size: "lg", windowClass: "operation-log-dialog", resolve: { host: function() { return { id: n, type: t } } } }) },
        p = function(n) { var i = t.defer(),
                r, e; return n && n.state == 0 ? (r = [], e = [], angular.forEach(n.items, function(n) { n.fromProductId ? r.push(n.fromProductId) : e.push(n.productId) }), f.getProductPackageByProductIds(e).success(function(t) { u.getProductsByProductIds(r).success(function(r) { angular.forEach(n.items, function(i) { var e, u, f, o;
                        i.fromProductId ? (e = _.find(r, function(n) { return n.id == i.fromProductId }), e && (u = angular.copy(i), i.productId = e.id, i.name = e.name, i.category = e.category, i.producer = e.producer, i.specification = e.specification, i.unit = e.unit, i.count = u.packageCount ? u.count / u.packageCount : 0, i.amount = u.amount, i.price = i.count && i.count > 0 ? Ares.priceToFixed(i.amount / i.count) : 0, i.isPackage = !0, i.toPackageCount = u.packageCount, i.toProductId = u.productId, i.toSpecification = u.specification, i.toUnit = u.unit, i.toPrice = u.price, i.toNumber = u.count, i.toAmount = u.amount)) : (f = _.find(t, function(n) { return n.fromProductId == i.productId }), f && (i.isPackage = i.fromProductId > 0, i.toPackageCount = f.count, i.toProductId = f.toProductId, i.toSpecification = f.toSpecification, i.toUnit = f.toUnit, i.toPrice = f.toPrice, i.toNumber = f.toNumber, i.toAmount = f.toAmount, o = _.find(n.items, function(n) { return n.productId == i.toProductId && i.isPackage }), o && (i.isPackage = !1))) });
                    i.resolve(!0) }) })) : i.resolve(!0), i.promise },
        w = e.isAllowed("featureRelation.salingOutStock"),
        b = function(n) { var t = !1; return n && (t = n.inOrderAction == 6 && w), t },
        k = function(n) { n.searchCriteria || (n.searchCriteria = {});
            n.inOrderActionSearchTypes = { pending: [{ text: "全部入库类型", value: "all" }, { text: "采购入库", value: "1" }, { text: "销售退货", value: "6" }, { text: "退领入库", value: "5" }, { text: "零散入库", value: "0" }], other: [{ text: "全部入库类型", value: "all" }, { text: "采购入库", value: "1" }, { text: "销售退货", value: "6" }, { text: "退领入库", value: "5" }, { text: "盘盈入库", value: "3" }, { text: "调拨入库", value: "2" }, { text: "拆包入库", value: "4" }, { text: "合包入库", value: "8" }, { text: "零散入库", value: "0" }] };
            n.inOrderActionOptions = n.inOrderActionSearchTypes.pending; var i = []; return n.basicData = {}, i.push(h.getProductCodeOptions().then(function(t) { n.productCodeOptions = t })), i.push(c.dealerDic.loadActive().then(function(t) { return o.isRootGroup && (t = t.filter(function(n) { return n.id !== -100 })), t.splice(0, 0, { name: "所属供应商" }), n.basicData.dealers = t, n.searchCriteria.dealer = "所属供应商", !0 })), i.push(c.warehouseDic.load().then(function(t) { return n.basicData.warehouses = t, !0 })), i.push(c.userNameDic.load().then(function(t) { return t = _.filter(t, function(n) { return !n.isInactive && n.isShow !== !1 }), t.splice(0, 0, { id: 0, name: "全部制单人" }), n.basicData.createUsers = t, n.searchCriteria.operatorId = 0, !0 })), i.push(c.currentOfficeWorkProviderDic.load().then(function(t) { return t.splice(0, 0, { id: "请选择", name: "请选择" }), n.basicData.providers = t, !0 })), i.push(c.currentOfficeWorkProviderDic.load().then(function(t) { return t.splice(0, 0, { id: 0, name: "全部经办人" }), n.basicData.receivers = t, n.searchCriteria.receiverId = 0, !0 })), i.push(c.currentOfficeWorkProviderIncludeAdminDic.load().then(function(t) { return _.each(t, function(n) { n.name === "超级管理员" && (n.name = "公司管理员", n.id = n.userID) }), t.splice(0, 0, { id: 0, name: "全部采购人" }), n.basicData.purchasers = t, n.searchCriteria.purchaserId = 0, !0 })), i.push(c.operatoryDic.load().then(function(t) { t = _.sortBy(t, "id"); var i = _.map(t, function(n) { return { value: n.description, name: n.description } }); return i.splice(0, 0, { value: "请选择", name: "请选择" }), n.basicData.operatories = i, !0 })), i.push(l.getDepartment().success(function(t) { var i = _.map(t, function(n) { return { value: n.itemName, name: n.itemName } }); return i.splice(0, 0, { value: "请选择", name: "请选择" }), n.basicData.departments = i, !0 })), i.push(c.sharedOfficeDic.load().then(function(t) { n.basicData.offices = t; var i = t.map(function(n) { return { value: n.abbreviation, name: n.name } }); return i.splice(0, 0, { value: "", name: "全部退货机构" }), n.basicData.relatedOffices = i, n.searchCriteria.relatedOffice = "", !0 })), n.deliverDataSource = [{ value: "请选择", name: "请选择" }], t.all(i) },
        d = function(n, t) { var i, r, u;
            n.warehouseId && (i = _.find(t.warehouses, function(t) { return t.id === n.warehouseId }), n.warehouseStr = i ? i.name : "", i && (n.hasPermission = e.getWarehousePermission(i)));
            n.state != null && (r = _.find(t.states, function(t) { return t.id === n.state }), n.stateStr = r ? r.name : "");
            n.receiverId && (u = _.find(t.basicData.receivers, function(t) { return t.id === n.receiverId }), n.receiverStr = u ? u.name : "");
            n.orderDate && (n.orderDateStr = moment(n.orderDate).format("YYYY-MM-DD"));
            n.deliverTypeStr = v(n.deliverType);
            n.inOrderAction === s.InOrderAction.TransferIn ? n.listLabelStr = n.receiverStr : n.inOrderAction === s.InOrderAction.UnSalesIn ? n.deliverType === s.InOrderDeliverType.WechatMall ? n.listLabelHtml = a.trustAsHtml('<div class="label label-lg label-success">微商城<\/div>') : n.listLabelStr = n.deliver : n.listLabelStr = n.inOrderAction === s.InOrderAction.UnTakeIn ? n.deliver : n.dealer }; return { viewOperationLog: y, restoreInventoryOrderItemPackage: p, isPatientRequiredForInOrder: b, initBaseData: k, setOrderProperties: d } }]);
supplychainModule.factory("inventoryOutOrderUtil", ["$q", "permissionProvider", "dataDicSvc", "warehouseSvc", "inventoryUtil", function(n, t, i, r, u) { "use strict"; var f = t.isAllowed("featureRelation.salingOutStock"),
        e = function(n) { var t = !1; return n && (t = n.outOrderAction == 5 && f), t },
        o = function(t) { t.searchCriteria = { outOrderAction: "all", state: "all", consigneeType: "all", consignee: "请选择", senderId: "0", dealer: "所属供应商", operatorId: "0", relatedOffice: "-1" }; var f = []; return t.basicData = {}, t.basicData.outOrderActionSearchTypes = { pending: [{ text: "全部出库类型", value: "all" }, { text: "销售出库", value: "5" }, { text: "领用出库", value: "1" }, { text: "采购退货", value: "6" }, { text: "报废出库", value: "7" }, { text: "零散出库", value: "0" }], other: [{ text: "全部出库类型", value: "all" }, { text: "销售出库", value: "5" }, { text: "领用出库", value: "1" }, { text: "采购退货", value: "6" }, { text: "报废出库", value: "7" }, { text: "盘亏出库", value: "3" }, { text: "调拨出库", value: "2" }, { text: "拆包出库", value: "4" }, { text: "合包出库", value: "8" }, { text: "零散出库", value: "0" }] }, t.outOrderActionOptions = t.basicData.outOrderActionSearchTypes.pending, f.push(i.dealerDic.loadActive().then(function(n) { n = n.filter(function(n) { return n.id !== -100 });
                n.splice(0, 0, { name: "所属供应商" });
                t.basicData.dealers = n })), f.push(i.currentOfficeWorkProviderDic.load().then(function(n) { var r = angular.copy(n),
                    i;
                r.splice(0, 0, { id: 0, name: "全部员工" });
                t.basicData.staffs = r;
                i = angular.copy(n);
                i.splice(0, 0, { id: 0, name: "全部经办人" });
                t.basicData.senders = i })), f.push(i.operatoryDic.load().then(function(n) { var i = _.sortBy(n, "id");
                i = _.map(i, function(n) { return { name: n.description } });
                i.splice(0, 0, { name: "全部诊室" });
                t.basicData.operatories = i })), f.push(i.departmentDic.load().then(function(n) { n = _.map(n, function(n) { return { name: n.itemName } });
                n.splice(0, 0, { name: "全部科室" });
                t.basicData.departments = n })), f.push(i.userNameDic.load().then(function(n) { var i = _.filter(n, function(n) { return !n.isInactive && n.isShow });
                i.splice(0, 0, { id: 0, name: "全部制单人" });
                t.basicData.createUsers = i })), f.push(i.sharedOfficeDic.load().then(function(n) { t.basicData.offices = n; var i = n.map(function(n) { return { value: n.abbreviation, name: n.name } });
                i.splice(0, 0, { value: "-1", name: "全部收货机构" });
                t.basicData.relatedOffices = i })), t.consigneeDataSource = [{ value: "请选择", name: "请选择" }], f.push(i.warehouseDic.loadActive().then(function(n) { t.basicData.warehouses = n })), f.push(r.getDealerWarehouseList().then(function(n) { n && n.data && (t.basicData.dealerWarehouses = angular.copy(n.data)) })), f.push(u.getProductCodeOptions().then(function(n) { t.productCodeOptions = n })), n.all(f) },
        s = function(n, i) { var r, u, f;
            n.warehouseId && (r = _.find(i.basicData.warehouses, function(t) { return t.id === n.warehouseId }), n.warehouseStr = r ? r.name : "", r && (n.hasPermission = t.getWarehousePermission(r)));
            n.state != null && (u = _.find(i.states, function(t) { return t.id == n.state }), n.stateStr = u ? u.name : "");
            n.senderId && (f = _.find(i.basicData.staffs, function(t) { return t.id === n.senderId }), n.senderName = f ? f.name : "");
            n.operateTime && (n.recordUpdatedTimeStr = moment(n.operateTime).format("YYYY-MM-DD HH:mm"));
            n.orderDate && (n.orderDateStr = moment(n.orderDate).format("YYYY-MM-DD")) }; return { isPatientRequiredForOutOrder: e, initBasicData: o, formatOrderUnit: s } }]);
supplychainModule.factory("inventoryTakeOrderUtil", ["$log", "$q", "$modal", "inventorySvc", function(n, t, i) { "use strict"; var r = function(n) { return i.open({ animation: !0, backdrop: "static", template: "<inventory-take-order-workflow-view><\/inventory-take-order-workflow-view>", controller: "InventoryTakeOrderWorkflowCtrl", windowClass: "inventory-take-order-workflow-view-wrapper", resolve: { host: function() { return { workflowItem: n } } } }).result }; return { browseWorkflowDialog: r } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f) { var e = this;
            this.$q = n;
            this.dataDicSvc = t;
            this.inventoryUtil = i;
            this.officeSvc = r;
            this.officeSelectorUtil = u;
            this.permissionProvider = f;
            this.initBasicData = function(n) { var t = [],
                    i; return t.push(e.dataDicSvc.currentOfficeWorkProviderDic.load().then(function(t) { n.receivers = t;
                    n.transferers = angular.copy(t);
                    n.receivers.unshift({ id: 0, name: "全部收货人" });
                    n.transferers.unshift({ id: 0, name: "全部发货人" }) })), t.push(e.dataDicSvc.userNameDic.load().then(function(t) { n.allCreateUsers = t;
                    n.createUsers = _.filter(t, function(n) { return !n.isInactive && n.isShow !== !1 });
                    n.createUsers.unshift({ id: 0, name: "全部制单人" }) })), t.push(e.dataDicSvc.warehouseDic.load().then(function(t) { t = _.filter(t, function(n) { return !n.isInactive });
                    n.toWarehouses = t;
                    n.fromWarehouses = angular.copy(t);
                    n.toWarehouses.unshift({ id: 0, name: "调入仓库" });
                    n.fromWarehouses.unshift({ id: 0, name: "调出仓库" }) })), t.push(e.dataDicSvc.officeDic.load().then(function(t) { n.offices = t })), t.push(e.inventoryUtil.getProductCodeOptions().then(function(t) { n.productCodeOptions = t })), i = e.officeSelectorUtil, n.isAcrossOfficeInventoryTransferEnabled && t.push(e.officeSvc.getNodesInGroup().success(function(t) { n.officeTreeData = i.setId(t) })), e.$q.all(t) } } return n.prototype.formatOrder = function(n, t) { var r, u, i, f;
            n.fromWarehouseId && (r = _.find(t.toWarehouses, function(t) { return t.id == n.fromWarehouseId }), r && (n.hasPermission = this.permissionProvider.getWarehousePermission(r)));
            n.recordCreatedUser && (u = _.find(t.createUsers, function(t) { return t.id == n.recordCreatedUser }), n.createUserName = u ? u.name : "");
            n.receiverId && (i = _.find(t.receivers, function(t) { return t.id == n.receiverId }), n.receiverName = i ? i.name : n.receiverName);
            n.transfererId && (i = _.find(t.receivers, function(t) { return t.id == n.transfererId }), n.transfererName = i ? i.name : n.transfererName);
            n.toOfficeId && (f = _.find(t.offices, function(t) { return t.id == n.toOfficeId }), n.toOfficeName = f ? f.name : "") }, n.$inject = ["$q", "dataDicSvc", "inventoryUtil", "officeSvc", "officeSelectorUtil", "permissionProvider"], n }();
    supplychainModule.factory("inventoryTransferOrderUtil", Ares.tsProvider(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o) { this.$q = n;
            this.aresNotification = t;
            this.warehouseUtil = i;
            this.dataDicSvc = r;
            this.aresConfirmDialog = u;
            this.officeOptionSvc = f;
            this.excelExportUtil = e;
            this.productUnitySvc = o } return n.prototype.checkOrderDateValid = function(n) { var t = !1; if (n)
                if (t = _.isString(n), _.isString(n)) t = moment(n, "YYYY-MM-DD", !0).isValid();
                else return _.isDate(n); return t }, n.prototype.checkOrderGreaterThanToday = function(n) { var t = Ares.today(),
                i = Ares.toDate(n); return i > t }, n.prototype.showInventoryErrorMessage = function(n, t) { n && ["InventoryOperationException", "NotInOrderInformationException", "AresBusinessException"].indexOf(n.name) > -1 ? this.aresConfirmDialog.warn({ message: n.message }) : this.aresNotification.error(t) }, n.prototype.initWarehouses = function(n) { var i = this,
                t = this.$q.defer(); return n ? this.dataDicSvc.warehouseDic.load().then(function(n) { t.resolve(n) }) : this.dataDicSvc.warehouseDic.loadActive().then(function(n) { n = i.warehouseUtil.filterWarehouses(n);
                t.resolve(n) }), t.promise }, n.prototype.initUsers = function() { var n = this.$q.defer(); return this.dataDicSvc.userNameDic.load().then(function(t) { n.resolve(t) }), n.promise }, n.prototype.initProviders = function() { var n = this.$q.defer(); return this.dataDicSvc.currentOfficeWorkProviderDic.load().then(function(t) { n.resolve(t) }), n.promise }, n.prototype.formatNumber = function(n, t) { var i = t ? parseInt(n) : parseFloat(n); return isNaN(i) ? "" : (i = Math.round(i * 100) / 100, i > 1e7 ? 1e7 : i) }, n.prototype.filterInventoryCostColumnms = function(n, t, i) { return t || (n = _.filter(n, function(n) { return i.indexOf(n.field) < 0 })), n }, n.prototype.getAllSubCategoriesIds = function(n) { var i = this,
                t = []; return n && (n.id > 0 && t.push(n.id), n.items && n.items.length > 0 && n.items.forEach(function(n) { t = t.concat(i.getAllSubCategoriesIds(n)) })), t }, n.prototype.getProductCategories = function() { var n = this.$q.defer(); return this.dataDicSvc.productCategoryDic.load().then(function(t) { _.each(t, function(n) { _.isString(n.levelCode) && (n.levelCode.length === 6 && (n.spriteCssClass = "iconfont icon-wenjianjia"), n.levelCode.length === 9 && (n.spriteCssClass = "iconfont icon-icon-test")) });
                n.resolve(t) }), n.promise }, n.prototype.getCategoryLevelByCategoryId = function(n, t) { var i = [],
                u = t.find(function(t) { return t.id == n }),
                r, f; return u && (i.push(u.name), u.parentId > 0 && (r = t.find(function(n) { return n.id == u.parentId }), r && (i.push(r.name), r.parentId > 0 && (f = t.find(function(n) { return n.id == r.parentId }), f && i.push(f.name))))), i.length > 0 ? i.reverse() : i }, n.prototype.setBatchesByProductId = function(n) { var t = [],
                i = _.groupBy(n.items, "productId"),
                r = _.keys(i); return n.inCount = 0, angular.forEach(r, function(r) { var f = i[r],
                    u = { id: r, name: f[0].name, producer: f[0].producer, specification: f[0].specification, code: f[0].code, unit: f[0].unit, inCount: 0, inStorageNum: 0, unInStorageNum: 0, price: 0, amount: 0, notes: f[0].notes, batches: f, isShowBatch: 0, deliveredStatus: f[0].deliveredStatus, deliveredNum: 0, referenceNotes: f[0].referenceNotes, refOutItems: f[0].refOutItems },
                    e;
                angular.forEach(f, function(t) { u.inCount += t.count;
                    u.unInStorageNum += t.unInStorageNum;
                    u.inStorageNum += t.inStorageNum;
                    u.deliveredNum += t.deliveredNum;
                    u.price += t.price;
                    u.amount += n.inOrderAction == 1 || n.inOrderAction == 6 ? t.businessAmount : t.amount;
                    (t.expiredDate || t.batchNumber) && (u.isShowBatch = 1) });
                e = Ares.priceToFixed(u.amount / u.inCount);
                u.price = u.price > e ? e : u.price;
                (n.inOrderAction == 1 || n.inOrderAction == 6) && (u.price = e);
                n.inCount += u.inCount;
                t.push(u) }), (n.inOrderAction == 1 || n.inOrderAction == 6) && (n.amount = n.businessAmount), n.products = t, n }, n.prototype.setOrderItemsByProductId = function(n, t, i) { t = angular.copy(t); var s = moment(Ares.today()).format("YYYY-MM-DD"),
                f = _.groupBy(t, "productId"),
                h = _.keys(f),
                e = [];
            angular.forEach(h, function(n) { var r = f[n],
                    t = angular.copy(r[0]);
                t.id = null;
                t.totalPrice = t.amount;
                t.oldTotalPrice = t.totalPrice;
                t.businessPrice = t.price;
                t.businessAmount = t.amount;
                t.deliveredNum = 0;
                t.toNumber = 0;
                t.toTotalPrice = 0;
                t.isLinkedCare = i == 2;
                t.orderDate = t.orderDate ? t.orderDate : s;
                angular.forEach(r, function(n) { t.unInStorageNum = n.unInStorageNum;
                    t.deliveredNum += n.deliveredNum });
                t.count = Math.min(t.count, t.unInStorageNum);
                e.push(t) }); var r = angular.copy(n),
                o = [],
                u = 0; return _.each(e, function(n) { o.push(n);
                u += n.amount }), r.items = o, r.amount = u, r.businessAmount = u, r }, n.prototype.orderProductsSortByIsChecked = function(n) { var t = n.products,
                i = _.filter(t, function(n) { return n.isChecked && n.unInStorageNum > 0 }),
                r = _.filter(t, function(n) { return !n.isChecked || n.unInStorageNum == 0 }); return n.products = i.concat(r), n }, n.prototype.getProductCodeOptions = function() { var t = this.$q.defer(),
                n = { allowInsideCode: !1, allowBarCode: !1, allowFirmCode: !1, validateCodeUniqueness: !1 }; return this.dataDicSvc.productCodeOptions.load().then(function(i) { _.isArray(i) && i.length > 0 && angular.forEach(i, function(t) { t.itemValue = t.itemValue || ""; switch (t.itemName) {
                        case "启用内部编码":
                            n.allowInsideCode = t.itemValue.toUpperCase() === "TRUE"; break;
                        case "启用物品条形码":
                            n.allowBarCode = t.itemValue.toUpperCase() === "TRUE"; break;
                        case "启用厂商编码":
                            n.allowFirmCode = t.itemValue.toUpperCase() === "TRUE"; break;
                        case "编码唯一性验证":
                            n.validateCodeUniqueness = t.itemValue.toUpperCase() === "TRUE" } });
                t.resolve(n) }), t.promise }, n.prototype.getGroupProcurementConfigs = function() { var n = this.$q.defer(); return this.dataDicSvc.inventoryConfigOptions.load().then(function(t) { var i = !1,
                    r = !1,
                    u;
                t && t.length > 0 && _.each(t, function(n) { n.itemName === "总部受理诊所采购申请" && n.itemValue === "True" ? i = !0 : n.itemName === "总部角色" && n.itemValue === "seller" && (r = !0) });
                u = { groupProcurementApplyEnabled: i, groupSalesEnabled: i && r };
                n.resolve(u) }), n.promise }, n.prototype.checkCanEditProcurementPrice = function() { var n = this.$q.defer(); return this.officeOptionSvc.getOfficeOption(this.officeOptionSvc.optionKeys.IsProcurementPriceLockEnabled).then(function(t) { n.resolve(!t) }), n.promise }, n.prototype.exportExcel = function(n) { var f = this.excelExportUtil.generateColumnSettings,
                e = this.excelExportUtil.Row,
                o = this.excelExportUtil.MainHeaderRow,
                s = this.excelExportUtil.HeaderCell,
                h = this.excelExportUtil.RegularCell,
                c = this.excelExportUtil.NumberCell,
                l = this.excelExportUtil.PriceCell,
                i = this.excelExportUtil.CenterCell,
                t = [],
                r, u;
            t.push(new o(n.headerRow.value, n.headerRow.colSpan));
            angular.forEach(n.contentRow, function(n) { var r = [];
                angular.forEach(n.row, function(n) { switch (n.cellType) {
                        case "centerCell":
                            r.push(new i(n.value, n.colSpan)); break;
                        case "headerCell":
                            r.push(new s(n.value, n.colSpan, n.textAlign)); break;
                        case "regularCell":
                            r.push(new h(n.value, n.colSpan)); break;
                        case "numberCell":
                            r.push(new c(n.value, n.format)); break;
                        case "priceCell":
                            r.push(new l(n.value, n.format)); break;
                        default:
                            r.push(new i(n.value, n.colSpan)) } });
                t.push(new e(r)) });
            r = { sheets: [{ title: n.title, columns: f(n.columnSettings), rows: t }] };
            u = new kendo.ooxml.Workbook(r);
            kendo.saveAs({ dataURI: u.toDataURL(), fileName: n.fileName + ".xlsx" }) }, n.prototype.checkProductInventoryCount = function(n) { var t = this.$q.defer(); return this.productUnitySvc.checkProductInventoryCount(n).then(function(n) { t.resolve(n) }), t.promise }, n.$inject = ["$q", "aresNotification", "warehouseUtil", "dataDicSvc", "aresConfirmDialog", "officeOptionSvc", "excelExportUtil", "productUnitySvc"], n }();
    supplychainModule.factory("inventoryUtil", Ares.tsProvider(n)) })(inventory || (inventory = {}));
supplychainModule.factory("inventoryWaybillUtil", ["$log", function() { "use strict"; var n = function(n, t) { var r = []; return _.each(n.items, function(n) { var t = _.pluck(n.waybillInfos, "waybillInfo");
                r = r.concat(t) }), r = _.uniq(r), _.each(r, function(n) { t.push({ waybillNum: n, items: [] }) }), i(n, t), n },
        t = function(n) { var t = angular.copy(n.products),
                i = _.filter(t, function(n) { return n.deliveredStatus == 0 && n.unInStorageNum > 0 }),
                r = _.filter(t, function(n) { return n.deliveredStatus == 1 && n.unInStorageNum > 0 }),
                u = _.filter(t, function(n) { return n.deliveredStatus == 2 && n.unInStorageNum > 0 }),
                f = _.filter(t, function(n) { return (n.deliveredStatus == 0 || n.deliveredStatus == 1 || n.deliveredStatus == 2) && n.unInStorageNum === 0 }),
                e = _.filter(t, function(n) { return n.deliveredStatus != 0 && n.deliveredStatus != 1 && n.deliveredStatus != 2 }),
                o = r.concat(u, i, f, e); return n.products = o, n },
        i = function(n, t) { _.each(n.items, function(n) { var i = _.uniq(_.pluck(n.waybillInfos, "waybillInfo"));
                _.each(i, function(i) { var u = angular.copy(n),
                        f = _.filter(n.waybillInfos, { waybillInfo: i });
                    u.deliveredNum = _.reduce(f, function(n, t) { return n + t.count }, 0);
                    r(u, i, t) }) }) },
        r = function(n, t, i) { _.each(i, function(i) { i.waybillNum == t && i.items.push(n) }) }; return { formatOrderByWaybillNumber: n, orderItemsSort: t } }]);
supplychainModule.factory("procurementApplyOrderUtil", ["$log", "$q", "$modal", "inventorySvc", "excelExportUtil", function(n, t, i, r, u) { "use strict"; var f = function(n) { return i.open({ animation: !0, backdrop: "static", template: "<procurement-apply-order-workflow-view><\/procurement-apply-order-workflow-view>", controller: "ProcurementApplyOrderWorkflowCtrl", windowClass: "modal-900w-dialog", resolve: { host: function() { return { workflowItem: n } } } }).result },
        e = function(n) { var h = u.generateColumnSettings,
                f = u.Row,
                c = u.MainHeaderRow,
                t = u.HeaderCell,
                i = u.RegularCell,
                e = u.NumberCell,
                l = h([100, 100, 100, 100, 100, 100]),
                r = [],
                o;
            r.push(new c("采购申请单", 6));
            r.push(new f([new t("申请编号："), new i(n.orderNo), new t("申请日期："), new i(n.applyTimeStr)]));
            r.push(new f([new t("申请人："), new i(n.applicantName), new t("审批人："), new i(n.workflowExecutorName), new t("经办人："), new i(n.operatorName)]));
            r.push(new f([new t("备注："), new i(n.notes, 5)]));
            r.push(new f([]));
            o = [new t("名称"), new t("品牌"), new t("规格"), new t("单位"), new t("申请数"), new t("实发数"), ];
            r.push(new f(o));
            _.each(n.items, function(n) { var t = [new i(n.name), new i(n.producer), new i(n.specification), new i(n.unit), new e(n.count), new e(n.handledCount)];
                r.push(new f(t)) }); var s = "采购申请单-" + n.orderNo,
                a = { sheets: [{ title: s, columns: l, rows: r }] },
                v = new kendo.ooxml.Workbook(a);
            kendo.saveAs({ dataURI: v.toDataURL(), fileName: s + ".xlsx" }) }; return { browseWorkflowDialog: f, exportExcel: e } }]);
supplychainModule.factory("procurementPayOrderUtil", ["$log", "$q", "$modal", "$sce", "inventorySvc", "$state", "enums", "excelExportUtil", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function(n) { return i.open({ animation: !0, backdrop: "static", template: "<procurement-pay-order-workflow-view><\/procurement-pay-order-workflow-view>", controller: "ProcurementPayOrderWorkflowCtrl", windowClass: "procurement-pay-order-workflow-view-wrapper", resolve: { host: function() { return { workflowItem: n } } } }).result },
        h = function(n) { var t = i.open({ animation: !0, backdrop: "static", template: "<operation-log-list-view><\/operation-log-list-view>", controller: "OperationLogListCtrl", size: "lg", windowClass: "operation-log-dialog", resolve: { host: function() { return { id: n, type: "ProcurementPayOrder" } } } }) },
        c = function(n) { var t = "",
                u = n.checkStatus,
                i; if (n.checkStatus > 0 && n.checkStatus != 2 && n.status != 5 && n.status != 6) switch (n.checkStatus) {
                case 1:
                    t = '<span class="label label-warning">待审批<\/span>'; break;
                case 2:
                    t = '<span class="label label-success">已审核<\/span>'; break;
                case 3:
                    t = '<span class="label label-danger">已拒绝<\/span>'; break;
                case 4:
                    t = '<span class="label label-warning">待提交<\/span>'; break;
                default:
                    t = '<span class="label label-default">未知<\/span>' } else switch (n.status) {
                case 0:
                    i = "待支付";
                    n.supplierType != e.OrganizationType.NormalDealer && n.settlementMethod === e.SettlementMethod.Monthly && (i = "待客服确认");
                    t = '<span class="label label-warning">' + i + "<\/span>"; break;
                case 1:
                    t = '<span class="label label-warning">待入库<\/span>'; break;
                case 2:
                    t = '<span class="label label-warning">部分入库<\/span>'; break;
                case 3:
                    t = '<span class="label label-success">已完成<\/span>'; break;
                case 4:
                    t = '<span class="label label-default">已作废<\/span>'; break;
                case 5:
                    t = '<span class="label label-warning">待下单<span>'; break;
                case 6:
                    t = '<span class="label label-warning">下单中<span>'; break;
                default:
                    t = '<span class="label label-warning">未知<\/span>' }
            return r.trustAsHtml(t) },
        l = function(n) { f.go("supplychain.inventory.inorder", { showInOrderDetail: { id: n.id, preInOrderType: 1, state: 0 } }) },
        a = function(n, t) { var y = o.generateColumnSettings,
                f = o.Row,
                p = o.MainHeaderRow,
                i = o.HeaderCell,
                r = o.RegularCell,
                l = o.NumberCell,
                e = o.PriceCell,
                w = y([50, 100, 150, 80, 150, 50, 100, 50, 100, 150]),
                u = [],
                s, h, c, a, v;
            u.push(new p("采购单", 10));
            u.push(new f([new i("下单机构：", 2, "left"), new r(n.officeName, 2), new i("供应商：", 1, "left"), new r(n.supplier, 3), new i("采购人：", 1, "left"), new r(n.purchaserName, 1)]));
            u.push(new f([new i("采购单号：", 2, "left"), new r(n.payOrderNo, 2), new i("单据日期：", 1, "left"), new r(n.orderDateStr, 3), new i("制单人：", 1, "left"), new r(n.userName, 1)]));
            u.push(new f([new i("备注：", 2, "left"), new r(n.notes, 8)]));
            s = [new i("名称"), new i("品牌"), new i("规格"), new i("单位"), new i("单价"), new i("数量"), new i("金额"), new i("备注")];
            t.allowInsideCode ? s.unshift(new i("序号"), new i("内部编码")) : s.unshift(new i("序号", 2));
            u.push(new f(s));
            h = 0;
            c = 0;
            _.each(n.items, function(n, i) { var o = [new r(n.name), new r(n.producer), new r(n.specification), new r(n.unit), new e(n.price), new l(n.number), new e(n.amount), new e(n.notes)];
                t.allowInsideCode ? o.unshift(new r(i + 1), new r(n.code)) : o.unshift(new r(i + 1, 2));
                u.push(new f(o));
                h += n.number;
                c += n.amount });
            u.push(new f([new i("合计", 7, "left"), new l(h), new e(c)]));
            u.push(new f([new i("折扣: " + n.couponAmount.toFixed(2) + "      运费: " + n.freight.toFixed(2) + "      应付: " + n.paymentAmount.toFixed(2) + "      实付: " + (n.showSettlementInfo ? n.actualAmount.toFixed(2) : "0.00"), 8, "left"), new i("采购人签字：", 2, "left")]));
            a = { sheets: [{ title: "采购单" + n.payOrderNo, columns: w, rows: u }] };
            v = new kendo.ooxml.Workbook(a);
            kendo.saveAs({ dataURI: v.toDataURL(), fileName: "采购单" + n.payOrderNo + ".xlsx" }) }; return { browseWorkflowDialog: s, viewOperationLog: h, getStatusLabelHtml: c, goToInOrder: l, exportExcel: a } }]);
supplychainModule.factory("productUtil", ["$log", "$q", "$modal", "aresNotification", "aresDialog", "dataDicSvc", function(n, t, i, r, u, f) { "use strict"; var e = function(n) { return n != null && n.indexOf("22") == 0 && n.length > 12 },
        o = function(n, r) { var u = t.defer(),
                f = i.open({ animation: !0, backdrop: "static", controller: "SkuPlatformReplaceDialogCtrl", template: "<sku-platform-replace-dialog-view><\/sku-inventory-poduct-spec-replace-edit-dialog-view>", windowClass: "sku-platform-replace-dialog-modal-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { currentSkus: angular.copy(r.products), platformSkus: angular.copy(n.products) } } } }); return f.result.then(function(t) { var i = t.addSkus || [],
                    f = t.replaceSkus || [];
                _.each(f, function(n) { var i = _.find(r.products, function(t) { return t.specAndUnit === n.toSpecAndUnit }),
                        t;
                    i && (_.extend(i, _.omit(n, "id", "productUnityId", "producerBarCode", "code", "freeField1", "freeField2", "freeField3")), i.producerBarCode || (i.producerBarCode = n.producerBarCode));
                    _.each(r.unityDealers, function(t) { var i = _.find(t.dealers, function(t) { return t.specAndUnit === n.toSpecAndUnit });
                        i && (i.specification = n.specification, i.unit = n.unit, i.specAndUnit = n.specAndUnit) });
                    t = _.find(r.productSalesPrices, function(t) { return t.productSpecAndUnit === n.toSpecAndUnit });
                    t && (t.productSpecification = n.specification, t.productUnit = n.unit, t.productSpecAndUnit = n.specAndUnit) });
                n.products = _.sortBy(i.concat(r.products), function(n) { return !n.isLinkedCare });
                n.categoryId = r.categoryId;
                n.category = r.category;
                n.id = r.id;
                _.each(r.unityDealers, function(n) { n.isPreferred = !1 });
                n.unityDealers = n.unityDealers.concat(r.unityDealers);
                n.isSalesEnabled = r.isSalesEnabled;
                n.productSalesPrices = r.productSalesPrices;
                n.isBatchNoEnabled = r.isBatchNoEnabled;
                n.isExpiredDateEnabled = r.isExpiredDateEnabled;
                n.onExpireDateWarnSwitch = r.onExpireDateWarnSwitch;
                n.isTakePriceSetEnabled = r.isTakePriceSetEnabled;
                n.takePriceUpRatio = r.takePriceUpRatio;
                n.valuationType = r.valuationType;
                n.isReplacing = !0;
                u.resolve(n) }), u.promise },
        s = function(n) { var t = i.open({ animation: !0, backdrop: "static", template: "<operation-log-list-view><\/operation-log-list-view>", controller: "OperationLogListCtrl", size: "lg", windowClass: "operation-log-dialog", resolve: { host: function() { return { id: n, type: "ProductUnity" } } } }) },
        h = function() { var i = t.defer(),
                n = {}; return f.systemItemDic.loadActive().then(function(t) { if (t) { var r = _.filter(t, { itemType: "物品自由项" });
                    r && (n.freeField1 = _.find(r, { itemName: "物品自由项1" }), n.freeField2 = _.find(r, { itemName: "物品自由项2" }), n.freeField3 = _.find(r, { itemName: "物品自由项3" })) } i.resolve(n) }), i.promise }; return { isLinkedCareProduct: e, openReplacePlatformSpuDialog: o, viewOperationLog: s, loadProductFreeFields: h } }]);
supplychainModule.factory("supplyChainPrintHandlerUtil", ["$log", "$q", "$modal", "dataDicSvc", "loginContext", "inventoryUtil", "inventoryInOrderUtil", "inventoryOutOrderUtil", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function(n) { var i = t.defer(); return r.officeDic.load().then(function(t) { var r = t.find(function(t) { return t.id == n });
                i.resolve(r) }), i.promise },
        h = function() { this.getOtherData = function(n) { var c = t.defer(),
                    i = n.baseData,
                    r = {}; if (i) { if (r.isPatientRequire = e.isPatientRequiredForInOrder(i), i.officeId && s(i.officeId).then(function(n) { n && (r.officeName = n.name) }), i.items.length > 0) { var l = 0,
                            a = 0,
                            f = !1,
                            o = !1,
                            h = !1;
                        i.items.forEach(function(n) {
                            (i.inOrderAction === 0 || i.inOrderAction === 6) && (n.price = n.businessAmount / n.count, n.amount = n.businessAmount);
                            l += n.count;
                            a += n.amount;
                            f = f || n.expiredDate;
                            o = o || n.batchNumber;
                            h = h || n.unicode });
                        r.totalCount = l;
                        r.totalAmount = a;
                        r.isExpireDateVisible = f;
                        r.isBatchNumberVisible = o;
                        r.isUnicodeVisible = h;
                        r.isShowPrice = i.inOrderAction != 5 && (!i.referenceOrderId || i.referenceOrderId > 0 && i.inOrderAction == 1 && u.isProcurementPriceAllowed) } r.isInventoryCostVisible = n.scope.isInventoryCostVisible } return c.resolve(r), c.promise };
            this.templateConfig = { configName: "InventoryInOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/inventory-in-order.html" } },
        c = function() { this.getOtherData = function(n) { var h = t.defer(),
                    r = n.baseData,
                    i = {}; if (r) { if (i.isPatientRequire = o.isPatientRequiredForOutOrder(r), r.officeId && s(r.officeId).then(function(n) { n && (i.officeName = n.name) }), r.items.length > 0) { var c = 0,
                            l = 0,
                            a = 0,
                            u = !1,
                            f = !1,
                            e = !1;
                        r.items.forEach(function(n) { var t = r.products.find(function(t) { return n.productId == t.id });
                            n.businessPrice = t ? t.businessPrice : 0;
                            c += n.count;
                            a += n.businessAmount;
                            l += n.amount;
                            u = u || n.expiredDate;
                            f = f || n.batchNumber;
                            e = e || n.unicode });
                        i.totalCount = c;
                        i.totalAmount = l;
                        i.totalBussinessAmount = a;
                        i.isExpireDateVisible = u;
                        i.isBatchNumberVisible = f;
                        i.isUnicodeVisible = e } i.isInventoryCostVisible = n.scope.isInventoryCostVisible;
                    i.recordCreatedTimeStr = moment(r.recordCreatedTime).format("YYYY-MM-DD HH:mm:ss") } return h.resolve(i), h.promise };
            this.templateConfig = { configName: "InventoryOutOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/inventory-out-order.html" } },
        l = function() { this.getOtherData = function(n) { var r = t.defer(),
                    i = n.baseData,
                    u = {}; return i && (i.officeId && s(i.officeId).then(function(n) { n && (u.officeName = n.name) }), i.items.length > 0 && i.items.forEach(function(n) { n.unOutStorageNum = n.inventoryCount >= n.unOutStorageNum ? n.unOutStorageNum : n.inventoryCount;
                    n.outCount = n.inventoryCount >= n.outCount ? n.outCount : n.inventoryCount })), r.resolve(u), r.promise };
            this.templateConfig = { configName: "InventoryOutOrderWithRef", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/inventory-out-order-with-ref.html" } },
        a = function() { this.getOtherData = function(n) { var e = t.defer(),
                    i = {}; if (n.baseData && (n.baseData.officeId && s(n.baseData.officeId).then(function(n) { n && (i.officeName = n.name) }), n.baseData.items.length > 0)) { var o = 0,
                        r = !1,
                        u = !1,
                        f = !1;
                    n.baseData.items.forEach(function(n) { o += n.count;
                        r = r || n.expiredDate;
                        u = u || n.batchNumber;
                        f = f || n.unicode });
                    i.totalCount = o;
                    i.isExpireDateVisible = r;
                    i.isBatchNumberVisible = u;
                    i.isUnicodeVisible = f } return e.resolve(i), e.promise };
            this.templateConfig = { configName: "InventoryTransferOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/inventory-transfer-order.html" } },
        v = function() { this.getOtherData = function(n) { var f = t.defer(),
                    i = {}; if (n.baseData && (n.baseData.officeId && s(n.baseData.officeId).then(function(n) { n && (i.officeName = n.name) }), n.baseData.details.length > 0)) { var r = 0,
                        u = 0;
                    n.baseData.details.forEach(function(n) { r += n.inventoryCount;
                        u += n.actualCount });
                    i.totalInventoryCount = r;
                    i.totalActualCount = u;
                    i.totalCountGap = u - r;
                    i.isExpireDateVisible = n.baseData.details.some(function(n) { return n.expiredDate });
                    i.isBatchNumberVisible = n.baseData.details.some(function(n) { return n.batchNumber });
                    i.isUnicodeVisible = n.baseData.details.some(function(n) { return n.unicode }) } return f.resolve(i), f.promise };
            this.templateConfig = { configName: "InventoryCheckOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/inventory-check-order.html" } },
        y = function() { this.getOtherData = function(n) { var o = t.defer(),
                    r = n.baseData,
                    h = new Date,
                    i = { totayStr: moment(h).format("YYYY-MM-DD HH:mm:ss"), orderDateStr: moment(r.orderDate).format("YYYY-MM-DD") },
                    u, e; return r && (r.officeId && s(r.officeId).then(function(n) { n && (i.officeName = n.abbreviation) }), f.getProductCodeOptions().then(function(n) { i.productCodeOptions = n }), u = 0, e = 0, i.items = [], r.procurementOrders.forEach(function(n) { n.procurementOrderItems.forEach(function(n) { u += n.number;
                        e += n.amount;
                        i.items.push(n) }) }), i.totalCount = u, i.totalAmount = e), o.resolve(i), o.promise };
            this.templateConfig = { configName: "ProcurementOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/procurement-payorder.html" } },
        p = function() { this.getOtherData = function(n) { var u = t.defer(),
                    e = n.baseData,
                    i = {},
                    r; return e && (f.getProductCodeOptions().then(function(n) { i.productCodeOptions = n }), r = 0, e.items.forEach(function(n) { r += n.count }), i.totalCount = r), u.resolve(i), u.promise };
            this.templateConfig = { configName: "InventoryTakeOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/inventory-take-order.html" } },
        w = function() { this.getOtherData = function(n) { var e = t.defer(),
                    o = n.baseData,
                    i = {},
                    r, u; return o && (f.getProductCodeOptions().then(function(n) { i.productCodeOptions = n }), r = 0, u = 0, o.items.forEach(function(n) { r += n.count;
                    u = n.amount }), i.totalCount = r, i.totalAmount = u), e.resolve(i), e.promise };
            this.templateConfig = { configName: "ProcurementReturnOrder", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/procurement-return-order.html" } },
        b = function() { this.getOtherData = function() { var n = t.defer(),
                    i = { totayStr: moment(new Date).format("YYYY-MM-DD HH:mm:ss") }; return n.resolve(i), n.promise };
            this.templateConfig = { configName: "", defaultTemplateUrl: "/app/common/components/print-template/supply-chain-print-template/procurement-applyorder.html" } }; return { inventoryInOrderHandler: h, inventoryOutOrderHandler: c, inventoryOutOrderWithRefHandler: l, inventoryTransferOrderHandler: a, inventoryCheckOrderHandler: v, procurementOrderHandler: y, inventoryTakeOrderHandler: p, procurementReturnOrderHandler: w, procurementApplyOrderHandler: b } }]);
supplychainModule.factory("supplyChainPrintUtil", ["$log", "$q", "$modal", "$sce", "$compile", "$timeout", "$templateRequest", "supplyChainPrintHandlerUtil", "practiceSvc", function(n, t, i, r, u, f, e, o, s) { "use strict"; var l = "/app/common/components/print-template/supply-chain-print-template/",
        a = function() { var i = angular.element("html"),
                n, t; return i.append('<iframe id="print-iframe-supply-chain" name="print-iframe"><\/iframe>'), n = window.frames["print-iframe"], t = '<html>                                    <head>                                        <title><\/title>                                    <\/head>                                    <body>                                        <div id="print-content-area"><\/div>                                    <\/body>                                <\/html>', n.document.write(t), n },
        v = function(n) { var t = a(),
                i = angular.element(t.document);
            i.find("#print-content-area").append(n.toString());
            i.ready(function() { t.print();
                angular.element("#print-iframe-supply-chain").remove() }) },
        y = function(n) { var i = t.defer(),
                r; return n ? (r = "SupplychainPrintTemplate", s.getSystemConfigByTypeAndName(r, n).success(function(n) { n && n.configValue ? s.getTemplateByCode(n.configValue).success(function(n) { n ? n.isPrivateTemplate ? i.resolve(n.templateContent) : n.templateCode ? e(l + n.templateCode).then(function(n) { i.resolve(n) }) : i.resolve(null) : i.resolve(null) }) : i.resolve(null) })) : i.resolve(null), i.promise },
        c = function(n) { this.printHandler = n;
            this.printTemplate = null;
            this.printData = {} };
    c.prototype = { print: function(n, i) { var r = this;
            r.printHandler && (r.printData.baseData = n, r.printData.scope = i, t.all([r.getOtherData(), r.getPrintTemplate()]).then(function() { r.generatePrintHtmlStr().then(function(n) { v(n) }) })) }, getOtherData: function() { var n = this,
                i = t.defer(); return n.printHandler.getOtherData ? n.printHandler.getOtherData(n.printData).then(function(t) { n.printData.otherData = t;
                i.resolve() }) : i.resolve(), i.promise }, getPrintTemplate: function() { var r = this,
                n = t.defer(),
                i; return r.printHandler.templateConfig ? (i = r.printHandler.templateConfig, i.configName ? y(i.configName).then(function(t) { t ? (r.printTemplate = t, n.resolve()) : i.defaultTemplateUrl ? e(i.defaultTemplateUrl).then(function(t) { r.printTemplate = t;
                    n.resolve() }) : n.reject() }) : i.defaultTemplateUrl ? e(i.defaultTemplateUrl).then(function(t) { r.printTemplate = t;
                n.resolve() }) : n.reject()) : n.reject(), n.promise }, generatePrintHtmlStr: function() { var i = t.defer(),
                n = this,
                e = n.printData.scope,
                o; return n.printData.scope = null, angular.extend(e, n.printData), o = u(n.printTemplate)(e), f(function() { var n = r.trustAsHtml(o[0].outerHTML);
                i.resolve(n) }), i.promise } }; var h = function(n) { return new c(n) },
        p = function(n) { var t = null; return n == "inOrder" ? t = new o.inventoryInOrderHandler : n == "outOrder" ? t = new o.inventoryOutOrderHandler : n == "transferOrder" ? t = new o.inventoryTransferOrderHandler : n == "checkOrder" ? t = new o.inventoryCheckOrderHandler : n == "takeOrder" ? t = new o.inventoryTakeOrderHandler : n == "returnOrder" && (t = new o.procurementReturnOrderHandler), h(t) },
        w = function(n, t) { var i = h(new o.inventoryInOrderHandler);
            i.print(n, t) },
        b = function(n, t) { n && n.items && (n.items = _.filter(n.items, function(n) { return n.count > 0 })); var i = h(new o.inventoryOutOrderHandler);
            i.print(n, t) },
        k = function(n, t) { var i = h(new o.inventoryOutOrderWithRefHandler);
            i.print(n, t) },
        d = function(n, t) { var i = h(new o.inventoryTransferOrderHandler);
            i.print(n, t) },
        g = function(n, t) { var i = h(new o.inventoryCheckOrderHandler);
            i.print(n, t) },
        nt = function(n, t) { var i = h(new o.procurementOrderHandler);
            i.print(n, t) },
        tt = function(n, t) { var i = h(new o.inventoryTakeOrderHandler);
            i.print(n, t) },
        it = function(n, t) { var i = h(new o.procurementReturnOrderHandler);
            i.print(n, t) },
        rt = function(n, t) { var i = h(new o.procurementApplyOrderHandler);
            i.print(n, t) }; return { getPrinterByHandler: h, getPrinterByType: p, printInventoryInOrder: w, printInventoryOutOrder: b, printInventoryOutOrderWithRef: k, printInventoryTransferOrder: d, printInventoryCheckOrder: g, printProcurementOrder: nt, printInventoryTakeOrder: tt, printProcurementReturnOrder: it, printProcurementApplyOrder: rt } }]);
supplychainModule.directive("inventorySystemItemEditView", ["$log", "$timeout", "dataDicSvc", function(n, t) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/inventory-system-item-edit-view.html", link: function(n, i) { var r, u = function() { r = Ares.validateForm(i.find("#ruleSettingForm"), { itemName: { required: !0, systemItemName: !0, maxlength: 20 } }, { itemName: { required: "请输入项目名称", systemItemName: "名称已被使用", maxlength: "项目名称不能超过20个字符" } }) },
                f = function() { i.find("#ruleSettingForm").valid() && n.saveSystemItem() },
                e = function() { jQuery.validator.addMethod("systemItemName", function(t) { var i = !0,
                            r; return t && (r = _.some(n.siblings, function(t) { return t.itemName === n.currentSystemItem.itemName && t.id !== n.currentSystemItem.id }), r && (i = !1)), i }, "名称已被使用！") };
            (function() { e();
                u();
                n.validAndSave = f;
                n.$watch("currentSystemItem", function() { r && Ares.clearError(i.find("#ruleSettingForm")) });
                t(function() { Ares.centerModal(i.closest(".modal-dialog")) }, 5) })() } } }]);
supplychainModule.directive("newInventoryHomeView", ["$log", "$timeout", "$state", "appNav", "$window", "eventAggregator", "tenantSvc", function(n, t, i, r, u, f, e) { return { restrict: "E", templateUrl: "/app/supplychain/views/new-inventory-home-view.html", link: function(n, t) { var i = function() { var n = t.find(".new-inventory-guide"),
                        i = localStorage.getItem("newInventoryHome_showGuide"),
                        r, u; if (!i) { n.show(); return } if (i !== "never") { if (r = moment(i), !r.isValid()) { n.show(); return } u = moment(moment().format("YYYY-MM-DD"));
                        u.isAfter(r) && n.show() } },
                r = function() { localStorage.setItem("newInventoryHome_showGuide", "never");
                    t.find(".new-inventory-guide").hide();
                    f.publish(f.events.InventoryNewGuideHideForever, null) },
                u = function() { localStorage.setItem("newInventoryHome_showGuide", moment().format("YYYY-MM-DD"));
                    t.find(".new-inventory-guide").hide() },
                o = function() { f.subscribe(n, f.events.HelpSlideShown, function() { t.find(".content-container").addClass("help-slide-shown") });
                    f.subscribe(n, f.events.HelpSlideHidden, function() { t.find(".content-container").removeClass("help-slide-shown") }) },
                h = function() { return e.GetTenantIsCustomizeOpen().then(function(t) { n.isCustomizeOpen = t.data;
                        e.getTenantOptionExtension().then(function(t) { n.extension = t.data }) }) },
                s = function() { var n = t.find(".ares-help-slide");
                    n.length > 0 && !n.hasClass("ares-help-slide-hidden") && t.find(".content-container").addClass("help-slide-shown") };
            (function() { i();
                o();
                s();
                n.hideGuideForever = r;
                n.hideGuideToday = u })() } } }]);
supplychainModule.directive("warehouseEditView", ["$log", "$timeout", "dataDicSvc", "providerSvc", "officeSvc", "loginContext", "enums", function(n, t, i, r, u, f, e) { return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/warehouse-edit-view.html", link: function(n, r) { var s, h = function() { s = Ares.validateForm(r.find("#warehouseForm"), { name: { required: !0, NotIncludeBlank: !0 } }, { name: { required: "请输入名称", NotIncludeBlank: "不能输入空格" } }) },
                c = function() { a();
                    l();
                    h() },
                l = function() { i.currentOfficeWorkProviderDic.load().then(function(t) { t = _.filter(t, function(n) { return n.show == !0 }); var i = r.find("#ownerId-drop").kendoMultiSelect({ dataTextField: "name", dataValueField: "id", dataSource: t }).data("kendoMultiSelect");
                        n.warehouse.ownerIds && r.find("#ownerId-drop").data("kendoMultiSelect").value(n.warehouse.ownerIds) }) },
                a = function() { u.getOfficeList().then(function(t) { var i = [],
                            u;
                        t.data.length > 1 && i.push({ id: "", name: "" });
                        angular.forEach(t.data, function(n) { i.push(n) });
                        f.roleType != "公司管理员" && (i = _.filter(i, function(n) { return n.id == f.officeId }));
                        u = r.find("#belongToOffice-drop");
                        u.css("width", "200px");
                        u.kendoDropDownList({ dataSource: i, filter: "contains", dataTextField: "name", dataValueField: "id", value: n.warehouse ? n.warehouse.officeId : null, select: function(t) { n.warehouse.officeId = this.dataItem(t.item)[this.options.dataValueField] || null } });
                        o() }) },
                v = function() { var i, t;
                    n.warehouse.grade == e.WarehouseGrade.Office.value ? (i = f.officeId, t = $("#belongToOffice-drop").data("kendoDropDownList"), t && t.value(i)) : (i = "", t = $("#belongToOffice-drop").data("kendoDropDownList"), t && t.value(i)) },
                y = function() { var i, u, t;
                    r.find("#warehouseForm").valid() && (i = r.find("#ownerId-drop").data("kendoDropDownList"), i && (n.warehouse.ownerId = i.value()), u = $("#belongToOffice-drop").data("kendoDropDownList"), u && (n.warehouse.officeId = u.value()), t = r.find("#ownerId-drop").data("kendoMultiSelect").value(), n.warehouse.ownerIds = t && t.length > 0 ? t : null, n.saveWarehouse(n.warehouse)) },
                o = function() { var t;
                    n.warehouse.grade != e.WarehouseGrade.Office.value ? (t = $("#belongToOffice-drop").data("kendoDropDownList"), t && t.enable(!1)) : (t = $("#belongToOffice-drop").data("kendoDropDownList"), t && t.enable(!0)) };
            (function() { n.save = y;
                n.$watch("warehouse", function() { n.warehouse && c() });
                n.$watch("warehouse.grade", function() { n.warehouse && n.warehouse.grade && (v(), o()) }) })();
            t(function() { Ares.centerModal(r.closest(".modal-dialog")) }, 5) } } }]);
supplychainModule.directive("warehouseListView", ["$log", "$q", "$timeout", "dataDicSvc", "enums", "loginContext", "aresModalShelf", "permissionProvider", "warehouseSvc", "gridOptionUtil", "appNav", "eventAggregator", function(n, t, i, r, u, f, e, o, s, h, c, l) { return { restrict: "E", templateUrl: "/app/supplychain/views/warehouse-list-view.html", controller: "WareHouseListCtrl", link: function(n) { var t = function(n) { var t = e.open({ title: "新增盘点单", titleIconClass: "iconfont icon-kucunpandian", template: "<inventory-check-order-edit-modal-view><\/inventory-check-order-edit-modal-view>", controller: "InventoryCheckOrderEditModalCtrl", confirmClose: !0, resolve: { host: function() { return { warehouse: angular.copy(n) } } } });
                    t.result.then(function(n) { n && (c.goToState("supplychain.inventory.check"), i(function() { l.publish(l.events.IventoryActionMenuChanged, n, "WareHouseListCtrl") }, 500)) }) },
                r = function(t) { n.searchCriteria.isInactive = !t;
                    i(function() { n.query() }) };
            (function() { n.hasPermission = !1;
                n.checkWarehouse = t;
                n.onSearchActiveChange = r;
                n.$watch("searchCriteria.name", function() { n.searchCriteria && n.searchCriteria.name != null && n.query() }) })() } } }]);
supplychainModule.directive("inventoryApplyOrderHomeView", ["$log", "$q", "$timeout", "dataDicSvc", function() { return { replace: !0, templateUrl: "/app/supplychain/views/apply-order/inventory-apply-order-home-view.html", controller: "InventoryApplyOrderHomeCtrl", link: function() {} } }]);
supplychainModule.directive("inventoryTakeOrderListView", ["$log", "$q", "$timeout", "$modal", "$window", "dataDicSvc", "aresSlidePanel", "aresConfirmDialog", "aresNotification", "aresDialog", "enums", "eventAggregator", "inventoryUtil", "aresModalShelf", "supplyChainPrintUtil", "loginContext", "$filter", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) { return { replace: !0, templateUrl: "/app/supplychain/views/apply-order/inventory-take-order-list-view.html", controller: "InventoryTakeOrderListCtrl", link: function(n, r) { var st = w("toInventoryTakeReceiverType"),
                s = function() { var n = v.open({ template: "<inventory-take-order-edit-dialog-view><\/inventory-take-order-edit-dialog-view>", controller: "InventoryTakeOrderEditDialogCtrl", title: "新增领用申请", titleIconClass: "iconfont icon-caigouoff", confirmClose: !0, resolve: { host: function() { return {} } } });
                    n.result.then(function() { f() }) },
                h = function(n) { var t = v.open({ template: "<inventory-take-order-edit-dialog-view><\/inventory-take-order-edit-dialog-view>", controller: "InventoryTakeOrderEditDialogCtrl", title: "编辑领用申请", titleIconClass: "iconfont icon-caigouoff", confirmClose: !0, resolve: { host: function() { return { takeOrderId: n.id } } } });
                    t.result.then(function() { f() }) },
                c = function(t) { o.warn({ message: "确定作废此申请单？", onConfirm: function() { n.cancelTakeOrder(t.id).then(function() { f() }) }, onCancel: function() {} }) },
                b = function(t) { o.warn({ message: "确定提交处理此申请单？", onConfirm: function() { n.submitHandleTakeOrder(t).then(function() { f() }) }, onCancel: function() {} }) },
                k = function(t) { o.warn({ message: "确定提交审批此申请单？", onConfirm: function() { n.submitWorkflowTakeOrder(t).then(function() { f() }) }, onCancel: function() {} }) },
                d = function(n) { var t = v.open({ template: "<inventory-take-order-edit-dialog-view><\/inventory-take-order-edit-dialog-view>", controller: "InventoryTakeOrderEditDialogCtrl", title: "新增领用申请", titleIconClass: "iconfont icon-caigouoff", confirmClose: !0, resolve: { host: function() { return { reCreateTakeOrderId: n.id } } } });
                    t.result.then(function() { f() }) },
                g = function(t) { y.printInventoryTakeOrder(t, n) },
                nt = function(n, t) { var i = n.id;
                    l.publish(l.events.ProductSelected, i, t.delegateTarget) },
                tt = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } },
                it = function() { e(); var n = angular.element(u);
                    n.on("resize", function() { e() }) },
                e = function() { var t = angular.element(u).height(),
                        i = t - 234,
                        n = r.find(".table-main");
                    n.height(i);
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(tt);
                    r.find("[data-toggle=tooltip]").tooltip() },
                rt = function() { n.searchCriteria.startDate = n.searchTimeRange.startDate;
                    n.searchCriteria.endDate = n.searchTimeRange.endDate;
                    n.onSearchTakeOrder() },
                ut = function(t) { var i = t.sender.value();
                    i != n.searchCriteria.status && (n.searchCriteria.status = i);
                    n.onSearchTakeOrder() },
                f = function() { var r = t.defer(); return n.searchTakeOrder().then(function() { i(function() { e();
                            r.resolve() }) }), r.promise },
                ft = function(n) { var t = window.event ? n.keyCode : n.which;
                    t === 13 && f() },
                et = function() { a.getProductCodeOptions().then(function(t) { n.productCodeOptions = t }) },
                ot = function(n) { n.showAll = !n.showAll;
                    i(function() { e() }, 0, !1) };
            (function() { n.isShowCreateTakeOrder = p.providerId > 0;
                n.onSelectProduct = nt;
                n.onSearchTimeRangeChanged = rt;
                n.onChangeStatus = ut;
                n.onSearchTakeOrder = f;
                n.onEnter = ft;
                n.onEditTakeOrder = h;
                n.onCancelTakeOrder = c;
                n.onSubmitHandleTakeOrder = b;
                n.onSubmitWorkflowTakeOrder = k;
                n.onReCreateTakeOrder = d;
                n.createTakeOrder = s;
                n.initTableView = e;
                n.printTakeOrder = g;
                n.showMoreTakeOrderItems = ot;
                it();
                et() })() } } }]);
supplychainModule.directive("inventoryTakeOrderEditDialogView", ["$log", "$q", "$timeout", "$window", "dataDicSvc", "$modal", "eventAggregator", "aresConfirmDialog", "aresDialog", "aresTreeViewUtil", "inventoryUtil", "aresNotification", "loginContext", "enums", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/apply-order/dialogs/inventory-take-order-edit-dialog/inventory-take-order-edit-dialog-view.html", link: function(n, t) { var r = t.find(".table-main-content"),
                u = function() { i(function() { var t = r.find("tr:first").find("input:first");
                        t.focus().select();
                        n.lastInputKeyDownIsEnter = !1 }, 0, !1) },
                f = function() { r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } }) },
                o = function(n, t) { var i = n.productId;
                    e.publish(e.events.ProductSelected, i, t.delegateTarget);
                    Ares.retainOnePopover() },
                s = function(i) { var r, f; if (i) { if (event && event.keyCode !== 13) return; if (!n.lastInputKeyDownIsEnter) return;
                        r = angular.element(i.currentTarget);
                        r.hasClass("productItemSearch") ? u() : r.closest("tr").hasClass("inventory-take-order-item-row") && (f = t.find(".sku-auto-complete-selector-view").find("input:first"), f.focus()) } else u() },
                h = function(t) { n.withCount = t;
                    n.$modalInstance.broadcast("WITH_COUNT_CHANGE", { withCount: t }) },
                c = function(t) { t && t.originalEvent && !t.originalEvent.repeat && (n.lastInputKeyDownIsEnter = t && (t.keyCode === 13 || t.key === "Enter")) },
                l = function() { n.editInventoryTakeOrder.receiverName = n.editInventoryTakeOrder.receiverType == v.InventoryTakeReceiverType.Department ? a.department : "" };
            (function() { n.skuAutoCompleteOptions = { mode: "takeOrder", isLinkedCare: null };
                n.onSelectedProduct = o;
                n.focusNextInput = s;
                n.onWithCountChange = h;
                n.initScrollbar = f;
                n.onInputKeyDown = c;
                n.receiverTypeonChange = l;
                n.initData() })() } } }]);
supplychainModule.controller("InventoryTakeOrderEditDialogCtrl", ["$log", "$q", "$scope", "$modalInstance", "host", "dataDicSvc", "$timeout", "inventorySvc", "enums", "aresNotification", "inventoryProductSvc", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; var p = function(n, t) { var u = _.find(i.editInventoryTakeOrder.items, function(t) { return t.productId === n.productId }),
                r; if (u) { t ? u.count++ : h.error("此物品已经在当前领用申请列表中！"); return } r = { productId: n.productId, name: n.name, pinyin: n.pinyin, specification: n.specification, producer: n.producer, unit: n.unit, code: n.code, producerCode: n.producerCode, barCode: n.barCode, category: n.category, count: n.count || 0, sumCount: n.sumCount };
            i.inventoryTakeOrderId && (r.orderId = i.inventoryTakeOrderId);
            r.count = 1;
            i.editInventoryTakeOrder.items.unshift(r);
            i.$modalInstance.broadcast("SKU_SELECT_ADDED", { productId: r.productId });
            i.withCount || c.searchProductsWithSumCountByProductIds([r.productId]).success(function(n) { var t = _.find(n, function(n) { return n.productId === r.productId });
                t && (r.sumCount = t.sumCount) });
            e(function() { i.initScrollbar() }, 0, !1);
            t || e(function() { i.focusNextInput() }) },
        w = function(n, t) { i.editInventoryTakeOrder.items.splice(n, 1);
            i.$modalInstance.broadcast("SKU_SELECT_REMOVED", { productId: t.productId });
            e(function() { i.initScrollbar() }, 0, !1) },
        a = function(n) { if (!Ares.ensureNotDuplicated("SaveInventoryTakeOrder")) return defered.reject(), defered.promise; if (v()) { var t = i.inventoryTakeOrderId ? o.updateTakeOrder : o.createTakeOrder;
                t(i.editInventoryTakeOrder).then(function(t) { var u = t.data;
                    h.success(n + "成功");
                    r.close(u);
                    Ares.sensors.track("InventoryTakeOrderAdd", { StartPage: "新建领用申请", PatientName: i.editInventoryTakeOrder.notes }) }).catch(function(t) { var i = t.data;
                    h.error(n + "失败") }) } },
        b = function() { i.editInventoryTakeOrder.status = s.InventoryApplicationStatus.WaitPend;
            a("保存") },
        k = function() { i.editInventoryTakeOrder.status = s.InventoryApplicationStatus.WaitHandle;
            a("提交") },
        d = function() { v() && (i.editInventoryTakeOrder.status = s.InventoryApplicationStatus.Pending, o.startWorkflowTakeOrder(i.editInventoryTakeOrder).then(function(n) { var t = n.data;
                h.success("审批提交成功");
                r.close(t);
                Ares.sensors.track("InventoryTakeOrderAdd", { StartPage: "新建领用申请" }) }).catch(function(n) { var t = n.data;
                h.error("审批提交失败") })) },
        v = function() { var n = i.editInventoryTakeOrder,
                t, r; return (n.receiverType == s.InventoryTakeReceiverType.Operatory && n.receiverName !== null && n.receiverName !== "" && (t = _.find(i.operatorys, function(t) { return t.description === n.receiverName }), t || (n.receiverName = "")), n.receiverType == s.InventoryTakeReceiverType.Department && n.receiverName !== null && n.receiverName !== "" && (r = _.find(i.departments, function(t) { return t.itemName === n.receiverName }), r || (n.receiverName = "")), n.receiverType == s.InventoryTakeReceiverType.Operatory && (n.receiverName === null || n.receiverName === "")) ? (h.error("领用申请单的代领诊室不能为空"), !1) : n.receiverType == s.InventoryTakeReceiverType.Department && (n.receiverName === null || n.receiverName === "") ? (h.error("领用申请单的代领科室不能为空"), !1) : !n.items || n.items.length === 0 ? (h.error("领用申请单的领用物品不能为空！"), !1) : n.items.some(function(n) { return !n.count }) ? (h.error("领用申请单的领用物品的数量不能为0！"), !1) : !i.isInventoryOverflowTakeEnabled && n.items.some(function(n) { return !n.sumCount || n.count > n.sumCount }) ? (h.error("领用申请单的领用物品的数量不能大于库存数量！"), !1) : !0 },
        g = function() { var n = []; return n.push(f.workflowDefinitionDic.load().then(function(n) { i.inventoryTakeOrderWorkflow = _.find(n, function(n) { return n.workflowType === s.WorkflowType.InventoryTake && !n.isDisabled == !0 }) })), n.push(f.officeSettingDic.load().then(function(n) { i.isConnectYonyouHrp = n.isConnectYonyouHrp;
                i.isInventoryOverflowTakeEnabled = n.isInventoryOverflowTakeEnabled })), n.push(f.operatoryDic.load().then(function(n) { i.operatorys = _.clone(n) })), n.push(f.departmentDic.load().then(function(n) { i.departments = _.clone(n) })), t.all(n) },
        y = function() { var n = _.pluck(i.editInventoryTakeOrder.items, "productId");
            c.searchProductsWithSumCountByProductIds(n).success(function(n) { _.each(i.editInventoryTakeOrder.items, function(t) { var i = _.find(n, function(n) { return n.productId === t.productId });
                    i && (t.sumCount = i.sumCount) }) }) },
        nt = function() { var n = t.defer(); return i.inventoryTakeOrderId ? o.getTakeOrder(i.inventoryTakeOrderId).success(function(t) { i.editInventoryTakeOrder = t;
                y();
                e(function() { i.initScrollbar() }, 0, !1);
                n.resolve() }) : i.reCreateTakeOrderId ? o.getTakeOrder(i.reCreateTakeOrderId).success(function(t) { i.editInventoryTakeOrder = t;
                i.editInventoryTakeOrder.id = 0;
                i.editInventoryTakeOrder.operatorId = 0;
                i.editInventoryTakeOrder.operatorName = null;
                i.editInventoryTakeOrder.recordCreatedTime = null;
                i.editInventoryTakeOrder.items && i.editInventoryTakeOrder.items.length && i.editInventoryTakeOrder.items.forEach(function(n) { n.id = 0;
                    n.orderId = 0 });
                y();
                e(function() { i.initScrollbar() }, 0, !1);
                n.resolve() }) : (i.editInventoryTakeOrder = { chargeOrderDetailId: u.chargeOrderDetailId, receiverType: "0", receiverName: "", orderNumber: "", applicantId: "", applicantName: "", notes: "", items: [] }, n.resolve()), n.promise },
        tt = function() { var n = t.defer(); return g().then(function() { return nt() }).then(function() { n.resolve() }), n.promise },
        it = function() { r.on("SKU_SELECT_ADD", function(n) { if (n && n.data) { var t = n.data.sku;
                    i.addSkuToList(t, !1) } });
            r.on("TAB_SWITCHED", function() { if (i.editInventoryTakeOrder) { var n = _.pluck(i.editInventoryTakeOrder.items, "productId");
                    r.broadcast("SKU_EXIST_LIST", { productIds: n }) } }) };
    (function() { u.chargeOrderDetailId && (i.chargeOrder = { chargeOrderBillNo: u.chargeOrderBillNo, chargeItemName: u.chargeItemName, takeUser: l.userName });
        i.withCount = !0;
        i.submitHandle = k;
        i.submitSave = b;
        i.submitWorkflow = d;
        i.inventoryTakeOrderId = u.takeOrderId;
        i.reCreateTakeOrderId = u.reCreateTakeOrderId;
        i.initData = tt;
        i.addSkuToList = p;
        i.removeSku = w;
        it() })() }]);
supplychainModule.directive("inventoryGroupProcurementApplyListView", ["$window", "aresDialog", "aresSlidePanel", "aresNotification", "$timeout", "eventAggregator", "enums", "aresModalShelf", "aresConfirmDialog", "productSvc", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; return { restrict: "E", templateUrl: "/app/supplychain/views/group-procurement/inventory-group-procurement-apply-list-view.html", controller: "InventoryGroupProcurementApplyListCtrl", link: function(t, c) { var y = c.find("#inventory-group-procurement-apply-list-left-list"),
                a = c.find("#inventory-group-procurement-apply-list-right-list"),
                v = function() { var i = angular.element(n).height(),
                        r;
                    r = t.showSearchBoxes ? i - 380 : i - 255;
                    t.groupSalesEnabled || (r -= 32);
                    y.height(r);
                    a.height(i - 215) },
                p = function() { var t = angular.element(n).height();
                    a.find(".table-main").height(t - 290) },
                w = function(n, i) { t.activeIndex = i;
                    t.currentApply = angular.copy(n);
                    t.state === 0 && (t.currentApply.pendingItems = _.filter(t.currentApply.items, function(n) { return n.handledCount < n.count }), t.currentApply.handledItems = _.filter(t.currentApply.items, function(n) { return n.handledCount >= n.count }), t.checkAllState.pending = !1, t.checkAllState.handled = !1, t.checkAllState.all = !1, t.checkAllState.hasInventory = !1, t.checkedCount = 0);
                    u(function() { p() }, 0, !1) },
                b = function(n) { t.state = n;
                    t.search() },
                k = function() { t.showSearchBoxes = !t.showSearchBoxes;
                    v() },
                d = function(n) { switch (n) {
                        case "pending":
                            _.each(t.currentApply.pendingItems, function(n) { n.checked = t.checkAllState.pending });
                            l(); break;
                        case "handled":
                            _.each(t.currentApply.handledItems, function(n) { n.checked = t.checkAllState.handled });
                            l(); break;
                        case "all":
                            _.each(t.currentApply.pendingItems, function(n) { n.checked = t.checkAllState.all });
                            _.each(t.currentApply.handledItems, function(n) { n.checked = t.checkAllState.all });
                            t.checkAllState.pending = t.checkAllState.all;
                            t.checkAllState.handled = t.checkAllState.all;
                            t.checkedCount = t.checkAllState.all ? t.currentApply.items.length : 0;
                            t.checkAllState.all && (t.checkAllState.hasInventory = !1); break;
                        case "hasInventory":
                            if (t.checkAllState.hasInventory) { t.checkAllState.all = !1; var i = 0;
                                _.each(t.currentApply.items, function(n) { n.checked = n.curOfficeInventoryCount > 0;
                                    n.checked && i++ });
                                t.checkedCount = i;
                                t.checkAllState.pending = _.every(t.currentApply.pendingItems, function(n) { return n.checked });
                                t.checkAllState.handled = _.every(t.currentApply.handledItems, function(n) { return n.checked }) } else _.each(t.currentApply.items, function(n) { n.checked = !1 }), t.checkedCount = 0, t.checkAllState.pending = !1, t.checkAllState.handled = !1 } },
                l = function() { var r = !0,
                        u = 0,
                        n, i;
                    _.each(t.currentApply.pendingItems, function(n) { n.checked ? u++ : r = !1 });
                    t.checkAllState.pending = r;
                    n = !0;
                    i = 0;
                    _.each(t.currentApply.handledItems, function(t) { t.checked ? i++ : n = !1 });
                    t.checkAllState.handled = n;
                    t.checkAllState.all = t.checkAllState.pending && t.checkAllState.handled;
                    t.checkedCount = u + i;
                    t.checkAllState.hasInventory = !1 },
                g = function(n) { t.searchCriteria.officeIds = _.pluck(n, "officeId");
                    t.page.pageIndex = 1;
                    t.search() },
                nt = function(n) { var i;
                    t.currentApply.pendingItems.length > 0 ? i = "确定将本单设置为已处理吗？还有一些物品的发货数没有达到机构的申请数量" : (i = "确定将本单设置为已处理吗？", (t.currentApply.purchaserCount > 0 || t.currentApply.transferCount > 0) && (i += "设置完毕后，"), t.currentApply.purchaserCount > 0 && (i += "采购订单物品数量将不可变更，订单不可取消。"), t.currentApply.transferCount > 0 && (i += "调拨单将无法作废。"));
                    s.warn({ message: i, onConfirm: function() { t.markAsCompleted(n).then(function() { t.search();
                                t.currentApply = null;
                                ot() }).catch(function(n) { var t = "设为已处理失败";
                                n.data.name === "InventoryOperationException" && (t = n.data.message);
                                r.error(t) }) }, onCancel: function() {} }) },
                tt = function(n) { n.keyCode === 13 && t.search() },
                it = function() { var n = angular.copy(t.currentApply),
                        i; if (n.items = _.filter(n.items, function(n) { return n.checked }), n.items.length === 0) { r.error("请选择物品"); return } i = o.open({ title: "新增调拨单", titleIconClass: "iconfont icon-zhuanhuan", template: "<inventory-transfer-order-edit-modal-view><\/inventory-transfer-order-edit-modal-view>", controller: "InventoryTransferOrderEditModalCtrl", resolve: { host: function() { return { supplier: null, isFromProcurementApply: !0, procurementApply: n } } } });
                    i.result.then(function() { t.search() }) },
                rt = function() { var f = t.currentApply.pendingItems,
                        e = t.currentApply.handledItems,
                        n = _.filter(f, function(n) { return n.checked }),
                        i = _.filter(e, function(n) { return n.checked }),
                        r, u; if (n.length + i.length === 0) { s.warn({ message: "请选择物品！" }); return } r = function(t, r) { var u = n.concat(i);
                        t && r.length > 0 && (u = _.filter(u, function(n) { return r.indexOf(n.productId) < 0 ? !0 : (n.checked = !1, !1) }));
                        _.each(u, function(n) { n.unDeliveryNum = n.handledCount >= n.count ? 0 : n.count - n.handledCount;
                            n.number = n.unDeliveryNum });
                        ut(u) };
                    t.checkCanEditProcurementPrice ? r() : (u = _.union(_.pluck(n, "productId"), _.pluck(i, "productId")), h.getProductDealersByProductIds({ productIds: u }).success(function(t) { var f = u; if (_.each(t, function(n) { n.price > 0 && (f = _.without(f, n.productId)) }), f.length === n.length + i.length) { s.warn({ message: "当前选择的物品没有供应商报价，无法添加至采购单" }); return } f.length > 0 ? s.confirm({ message: '当前选择的物品有 <span class="enyo-text-warning">' + f.length + "<\/span> 件没有供应商报<br>是否移除后继续创建采购单？" }).then(function() { r(!0, f) }) : r() })) },
                ut = function(n) { var i = t.currentApply,
                        r = { officeId: i.officeId, officeName: i.officeName, procurementApplyOrderId: i.id, applyOrder: angular.copy(i) },
                        u = o.open({ title: "新增采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-edit-modal-view><\/procurement-order-edit-modal-view>", controller: "ProcurementOrderEditModalCtrl", resolve: { dataHost: function() { return { procurementPayOrderProductItems: n, applyOrderParams: r, source: e.ProcurementPayOrderSource.PurchaseApply } } }, confirmClose: !0 });
                    u.result.then(function(n) { n && ft(n);
                        t.search() }) },
                ft = function(n) { var r = i.open("<procurement-order-mall-cart-view><\/procurement-order-mall-cart-view>", "ProcurementOrderMallCartCtrl", { dataHost: function() { return { payOrderNo: n.split(":")[0], ownerOfficeId: n.split(":")[1] } } }, t) },
                et = function(n, t) { var i = n.productId;
                    f.publish(f.events.ProductSelected, i, t.delegateTarget) },
                ot = function() { t.isEdit || f.publish(f.events.RefreshProcurementHint, {}, "ProcurementHome") };
            (function() { t.showSearchBoxes = !1;
                t.checkAllState = { pending: !1, handled: !1, all: !1, hasInventory: !1 };
                t.checkedCount = 0;
                t.onSelectApply = w;
                t.toggleSearchBoxes = k;
                t.switchState = b;
                t.onCheckAllToggle = d;
                t.onItemChecked = l;
                t.onMarkAsCompleted = nt;
                t.onEnter = tt;
                t.onOfficeSelected = g;
                t.createTransferOrder = it;
                t.onSelectProduct = et;
                t.transferPurchaseOrder = rt;
                t.initBasicData().then(function() { v();
                    t.search() }) })() } } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n) { this.$timeout = n;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/group-procurement/mall-quotation-management/quotation-product-list-view.html";
            this.controller = "QuotationProductListCtrl";
            this.link = function(n, t) { var r = function(r) { var u = t.find(r.target);
                        u.prop("checked") ? (n.uiState.checkAll = !0, _.each(n.quotationProducts, function(n) { n.isCanUpdateStatus && (n.checked = !0) })) : (n.uiState.checkAll = !1, _.each(n.quotationProducts, function(n) { n.checked = !1 }));
                        i() },
                    i = function() { n.uiState.enabledChecked = _.some(n.quotationProducts, function(n) { return n.checked }) },
                    u = function() { var i = t.find("#quotation-products-operate-btn");
                        i.tooltip({ template: '<div class="tooltip tooltip-danger" role="tooltip"><div class="tooltip-arrow"><\/div><div class="tooltip-inner"><\/div><\/div>' }).on("show.bs.tooltip", function(t) { n.uiState.enabledChecked && t.preventDefault() }) };
                (function() { u();
                    n.toggleCheckAll = r;
                    n.checkCanOperate = i })() } } return n.$inject = ["$timeout"], n }();
    supplychainModule.directive("quotationProductListView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u) { this.$scope = n;
            this.loginContext = t;
            this.aresNotification = i;
            this.$sce = r;
            this.procurementSvc = u;
            n.uiState = { enabledChecked: !1, checkAll: !1 };
            n.quoteStatusEnums = { PreCommit: 0, PreCheck: 1, RefuseCommit: 3, PreAgreePrice: 4, PreConfirm: 5, RefuseConfirm: 6, Confirmed: 7 };
            n.page = { index: 1, size: 20, totalCount: 0 };
            n.searchCriteria = { isGroup: t.isGroup, pageIndex: 1, pageSize: 20, status: -1 };
            n.quotationProducts = [];
            this.initDateRange();
            this.search() } return n.prototype.initDateRange = function() { var n = Ares.today(),
                i = moment(n).startOf("month").toDate(),
                t = { startDate: i, endDate: n };
            this.$scope.searchDateRange = { startDate: moment(t.startDate).format("YYYY-MM-DD"), endDate: moment(t.endDate).format("YYYY-MM-DD") } }, n.prototype.initItemStatusHtml = function(n) { var t = ""; switch (n.quoteStatus) {
                case 0:
                    t = '<span class="enyo-text-warning">待提交<\/span>'; break;
                case 1:
                    t = '<span class="enyo-text-warning">待报价<\/span>'; break;
                case 3:
                    t = '<span class="enyo-text-danger">已拒绝<\/span>'; break;
                case 4:
                    t = '<span class="enyo-text-warning">待报价<\/span>'; break;
                case 5:
                    t = '<span class="enyo-text-warning">待确认<\/span>'; break;
                case 6:
                    t = '<span class="enyo-text-danger">拒绝报价<\/span>'; break;
                case 7:
                    t = '<span class="enyo-text-success">已完成<\/span>' } n.statusHtml = this.$sce.trustAsHtml(t) }, n.prototype.search = function() { var n = this;
            this.$scope.searchCriteria && this.$scope.searchDateRange && (this.$scope.searchCriteria.applyStartTime = this.$scope.searchDateRange.startDate, this.$scope.searchCriteria.applyEndTime = this.$scope.searchDateRange.endDate, this.$scope.page && (this.$scope.searchCriteria.pageIndex = this.$scope.page.index, this.$scope.searchCriteria.pageSize = this.$scope.page.size), this.procurementSvc.searchQuotationProducts(this.$scope.searchCriteria).success(function(t) { t && (n.$scope.page = { index: t.pageIndex, size: t.pageSize, totalCount: t.total }, n.$scope.quotationProducts = t.list, _.each(n.$scope.quotationProducts, function(t) { n.initItemStatusHtml(t) })) })) }, n.prototype.updateStatus = function(n, t, i) { var r = this,
                e = [],
                u, f; if (t) { if (e = [t], n != this.$scope.quoteStatusEnums.PreCommit && n != this.$scope.quoteStatusEnums.PreConfirm) { this.aresNotification.error("当前申请状态不支持更新"); return } i ? n == this.$scope.quoteStatusEnums.PreCommit ? n = this.$scope.quoteStatusEnums.PreAgreePrice : n == this.$scope.quoteStatusEnums.PreConfirm && (n = this.$scope.quoteStatusEnums.Confirmed) : n == this.$scope.quoteStatusEnums.PreCommit ? n = this.$scope.quoteStatusEnums.RefuseCommit : n == this.$scope.quoteStatusEnums.PreConfirm && (n = this.$scope.quoteStatusEnums.RefuseConfirm) } else { if (n != this.$scope.quoteStatusEnums.PreAgreePrice && n != this.$scope.quoteStatusEnums.RefuseCommit && n != this.$scope.quoteStatusEnums.Confirmed && n != this.$scope.quoteStatusEnums.RefuseConfirm) { this.aresNotification.error("不能批量更新至当前状态"); return } if (u = _.filter(this.$scope.quotationProducts, function(n) { return n.checked }), !u || u.length == 0) { this.aresNotification.error("请选择物品"); return } if ((n == this.$scope.quoteStatusEnums.PreAgreePrice || n == this.$scope.quoteStatusEnums.RefuseCommit) && (f = _.some(u, function(n) { return n.quoteStatus != r.$scope.quoteStatusEnums.PreCommit }), f)) { this.aresNotification.error("请确认选择的都是待提交的记录"); return } if ((n == this.$scope.quoteStatusEnums.Confirmed || n == this.$scope.quoteStatusEnums.RefuseConfirm) && (f = _.some(u, function(n) { return n.quoteStatus != r.$scope.quoteStatusEnums.PreConfirm }), f)) { this.aresNotification.error("请确认选择的都是待确认的记录"); return } e = _.map(u, function(n) { return n.id }) } this.procurementSvc.updateQuotationStatus(n, e).success(function(n) { n ? (r.aresNotification.success("更新成功"), r.$scope.uiState = { enabledChecked: !1, checkAll: !1 }, r.search()) : r.aresNotification.error("更新失败") }) }, n.$inject = ["$scope", "loginContext", "aresNotification", "$sce", "procurementSvc"], n }();
    supplychainModule.controller("QuotationProductListCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n) { var t = this;
            this.$timeout = n;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/group-procurement/suppler-view/inventory-group-procurement-supplier-view.html";
            this.controller = "InventoryGroupProcurementSupplierCtrl";
            this.link = function(n, i) {
                function s(n) { var t = function(n) { e.$timeout(function() { n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(o) }) }; switch (n) {
                        case "officeList":
                            t(f); break;
                        case "supplierList":
                            t(u); break;
                        case "mainTable":
                            t(r); break;
                        default:
                            [f, u, r].forEach(function(n) { t(n) }) } } var e = t,
                    r = i.find(".main-table"),
                    u = i.find(".supplier-list"),
                    f = i.find(".office-list"),
                    o = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } };
                (function() { n.updateScrollbar = s })() } } return n.$inject = ["$timeout"], n }();
    supplychainModule.directive("inventoryGroupProcurementSupplierView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { var p = this;
            this.$scope = n;
            this.officeSvc = t;
            this.officeSelectorUtil = i;
            this.$q = r;
            this.loginContext = u;
            this.eventAggregator = f;
            this.aresModalShelf = e;
            this.procurementApplyOrderSvc = o;
            this.$timeout = s;
            this.aresNotification = h;
            this.inventoryUtil = c;
            this.enums = l;
            this.organizationSvc = a;
            this.aresSlidePanel = v;
            this.excelExportUtil = y;
            n.uiState = { checkAll: !1, isEdit: !1, selectedProductCount: 0, visibleProductCount: 0, showProductCode: !1, canEditProcurementPrice: !1 };
            n.officeTreeInstance = null;
            n.selectedSupplier = { id: null, name: null };
            this.initBaseData().then(function() { p.getPreHandleSuppliers().then(function() { n.selectedSupplier = angular.copy(n.suppliers[0]);
                    p.onSupplierIdChange() }) }) } return n.prototype.initBaseData = function() { var n = this,
                t = []; return t.push(this.officeSvc.getSelfAndChildOfficesByGroupId(this.loginContext.officeId, !1).success(function(t) { return n.officeSelectorUtil.setId(t), n.officeSelectorUtil.setExtraFields(t), n.$scope.officeMap = n.officeSelectorUtil.flattenToMap(t), !0 })), t.push(this.inventoryUtil.getProductCodeOptions().then(function(t) { return n.$scope.uiState.showProductCode = t.allowInsideCode, !0 })), t.push(this.inventoryUtil.checkCanEditProcurementPrice().then(function(t) { n.$scope.uiState.canEditProcurementPrice = t })), this.$q.all(t) }, n.prototype.getPreHandleSuppliers = function() { var n = this,
                t = this.$q.defer(); return this.procurementApplyOrderSvc.getPreHandleSuppliers().success(function(i) { var r, u; if (!i || Object.keys(i).length === 0) { n.$scope.selectedSupplier = { id: 0, name: "" };
                    n.$scope.suppliers = [];
                    t.reject(!1); return } r = [];
                _.each(i, function(n, t) { r.push({ id: parseInt(t), name: i[t] }) });
                u = _.findIndex(r, function(n) { return n.name === "无供应商" });
                u > -1 && r.push(r.splice(u, 1)[0]);
                n.$scope.suppliers = r;
                t.resolve(!0) }), t.promise }, n.prototype.search = function() { var n = this,
                t = this.$q.defer(); return this.procurementApplyOrderSvc.getPlanDetailsBySupplierId(this.$scope.selectedSupplier.id).success(function(i) { var r = {},
                    f, e, u;
                i.forEach(function(n) { r[n.officeId] = r[n.officeId] || {};
                    r[n.officeId][n.productId] = r[n.officeId][n.productId] || [];
                    r[n.officeId][n.productId].push(n) });
                f = [];
                e = [];
                Object.keys(r).forEach(function(t) { var i = { officeId: parseInt(t), officeName: "", checkAll: !1, products: [], visible: !0 };
                    Object.keys(r[t]).forEach(function(u) { var f = r[t][u][0];
                        i.officeName = f.officeName; var o = { productId: f.productId, name: f.name, producer: f.producer, specification: f.specification, unit: f.unit, code: f.code, applyCount: 0, handledCount: 0, count: 0, officeId: f.officeId, supplierId: f.supplierId, supplier: f.supplier, price: f.price, isNotAgreedProduct: f.isNotAgreedProduct, applyItems: [], visible: !0, dealerCounts: {} },
                            h = 0,
                            c = 0,
                            s = 0;
                        r[t][u].forEach(function(n) { h += n.applyCount;
                            c += n.handledCount;
                            s += n.count;
                            o.applyItems.push(n) });
                        o.applyItems = _.sortBy(o.applyItems, "applyOrderDate");
                        o.applyCount = h;
                        o.handledCount = c;
                        o.count = s;
                        o.dealerCounts[n.$scope.selectedSupplier.id] = s;
                        i.products.push(o);
                        e.push(o) });
                    f.push(i) });
                n.$scope.groupedData = f;
                n.$scope.products = e;
                n.$scope.uiState.visibleProductCount = e.length;
                u = [];
                _.each(f, function(t) { var f = n.$scope.officeMap[t.officeId],
                        i, r;
                    u.push(f);
                    f.parentId && (i = n.$scope.officeMap[f.parentId], i && (u.indexOf(i) < 0 && u.push(i), i.parentId && (r = n.$scope.officeMap[i.parentId], r && u.indexOf(r) < 0 && u.push(r)))) });
                n.$scope.officeTreeData = n.officeSelectorUtil.unflatten(u);
                n.$scope.uiState.selectedProductCount = 0;
                n.$scope.uiState.checkAll = !1;
                t.resolve(!0);
                n.$timeout(function() { n.$scope.officeTreeInstance.checkByIds(_.pluck(u, "officeId"));
                    n.$scope.officeTreeInstance.expandAll();
                    n.$scope.updateScrollbar() }, 100, !1);
                t.resolve(!0) }), t.promise }, n.prototype.onSupplierIdChange = function() { var t = this,
                n, i; return (this.$scope.uiState.isEdit = !1, n = this.$q.defer(), !this.$scope.suppliers) ? (n.reject(!1), n.promise) : (i = _.find(this.$scope.suppliers, function(n) { return n.id === t.$scope.selectedSupplier.id }), !i) ? (n.reject(!1), n.promise) : (this.$scope.selectedSupplier.name = i.name, this.$scope.selectedSupplier.id === 0 ? this.search().then(function() { n.resolve(!0) }) : this.organizationSvc.get(this.$scope.selectedSupplier.id).success(function(i) { t.$scope.selectedSupplier.type = i.type;
                t.$scope.selectedSupplier.settlementMethod = i.settlementMethod;
                t.search().then(function() { n.resolve(!0) }) }), n.promise) }, n.prototype.onOfficeChecked = function() { var t = this,
                i = this.$scope.officeTreeInstance.getCheckedData(),
                n = _.pluck(i, "officeId");
            this.$scope.groupedData.forEach(function(t) { t.visible = n.indexOf(t.officeId) > -1 });
            this.$scope.uiState.visibleProductCount = this.$scope.products.reduce(function(t, i) { return i.visible = n.indexOf(i.officeId) > -1, i.visible ? t + 1 : t }, 0);
            this.checkSelectStatus();
            this.$timeout(function() { t.$scope.updateScrollbar("mainTable") }, 0, !1) }, n.prototype.toggleDetail = function(n) { var t = this;
            this.$scope.groupedData.forEach(function(n) { n.products.forEach(function(n) { n.showDetail = !1 }) });
            n.showDetail = !0;
            this.$timeout(function() { t.$scope.updateScrollbar("mainTable") }, 0, !1) }, n.prototype.showProductPopup = function(n, t) { t.stopPropagation();
            this.eventAggregator.publish(this.eventAggregator.events.ProductSelected, n.productId, t.delegateTarget) }, n.prototype.toggleProductCheck = function(n, t) { t.stopPropagation();
            n.checked = !n.checked;
            this.checkSelectStatus() }, n.prototype.toggleCheckAll = function() { var n = this;
            this.$scope.products.forEach(function(t) { t.checked = n.$scope.uiState.checkAll });
            this.checkSelectStatus() }, n.prototype.toggleOfficeCheckAll = function(n) { n.products.forEach(function(t) { t.checked = n.checkAll });
            this.checkSelectStatus() }, n.prototype.checkSelectStatus = function() { var n = this.$scope.products.filter(function(n) { return n.checked && n.visible });
            this.$scope.uiState.selectedProductCount = n.length;
            this.$scope.uiState.checkAll = this.$scope.uiState.selectedProductCount === this.$scope.uiState.visibleProductCount;
            this.$scope.groupedData.forEach(function(n) { n.checkAll = n.products.every(function(n) { return n.checked }) }) }, n.prototype.edit = function() { this.$scope.uiState.isEdit = !0 }, n.prototype.save = function() { var n = this,
                t = [];
            this.$scope.products.forEach(function(n) { var i = n.count;
                n.applyItems.forEach(function(r, u) { r.count = r.applyCount - r.handledCount < i ? u === n.applyItems.length - 1 ? i : r.applyCount - r.handledCount : i;
                    i - r.count <= 0 ? i = 0 : i -= r.count;
                    r.price = n.price;
                    t.push({ id: r.id, applyOrderId: r.applyOrderId, applyOrderItemId: r.applyOrderItemId, applyOrderNo: r.applyOrderNo, productId: r.productId, price: r.price, supplierId: r.supplierId, supplier: r.supplier, count: r.count, isDelete: !1 }) }) });
            this.procurementApplyOrderSvc.saveProcurementPlanDetails(t).success(function() { n.aresNotification.success("保存成功");
                n.$scope.products.forEach(function(t) { t.dealerCounts[n.$scope.selectedSupplier.id] = t.applyItems.reduce(function(n, t) { return n + t.count }, 0) }) });
            this.$scope.uiState.isEdit = !1 }, n.prototype.switchProductSupplier = function(n, t, i) { var r = this,
                f = n.products[t],
                u; if (f.supplierId === i.dealerId) return this.aresNotification.error("【" + i.dealerName + "】已经是当前供应商，不能切换");
            n.products.splice(t, 1);
            this.$scope.products = this.$scope.products.filter(function(n) { return n.productId !== f.productId });
            u = [];
            f.applyItems.forEach(function(n) { var t = { id: n.id, applyOrderId: n.applyOrderId, applyOrderItemId: n.applyOrderItemId, applyOrderNo: n.applyOrderNo, productId: n.productId, price: n.price, count: 0, supplierId: n.supplierId, supplier: n.supplier, isDelete: !0 },
                    r = _.extend({}, t, { id: 0, supplierId: i.dealerId, supplier: i.dealerName, price: i.price, count: n.count, isDelete: !1 });
                u.push(t);
                u.push(r) });
            this.procurementApplyOrderSvc.saveProcurementPlanDetails(u).success(function() { r.aresNotification.success("保存成功");
                r.getPreHandleSuppliers().then(function() { var t = _.find(r.$scope.suppliers, function(n) { return n.id === r.$scope.selectedSupplier.id });
                    t ? (r.checkSelectStatus(), r.$scope.uiState.visibleProductCount--, n.visible = n.products.length > 0) : (r.$scope.selectedSupplier = angular.copy(r.$scope.suppliers[0]), r.search()) }) }) }, n.prototype.splitProductSupplier = function(n, t, i) { var r = this,
                e = angular.copy(n.products[t]),
                u = [],
                o = _.values(i),
                f;
            this.$scope.selectedSupplier.id === 0 && o.push({ dealerId: 0, dealerName: "无供应商", price: 0 });
            o.forEach(function(n) { e.applyItems.forEach(function(t, i) { var r;
                    t.allocatedCount = t.allocatedCount || 0; var f = t.applyCount - t.handledCount - t.allocatedCount,
                        s = n.dealerId === t.supplierId ? t.id : 0,
                        o = f <= n.count && i < e.applyItems.length - 1 ? f : n.count;
                    n.dealerId === 0 && (o = f);
                    r = { id: s, applyOrderId: t.applyOrderId, applyOrderItemId: t.applyOrderItemId, applyOrderNo: t.applyOrderNo, productId: t.productId, price: n.price, count: o, supplierId: n.dealerId, supplier: n.dealerName, isDelete: !1 };
                    n.count -= r.count;
                    t.allocatedCount += r.count;
                    u.push(r) }) });
            f = _.filter(u, function(n) { return n.supplierId === r.$scope.selectedSupplier.id });
            _.every(f, function(n) { return n.count === 0 }) && _.each(f, function(n) { n.isDelete = !0 });
            this.procurementApplyOrderSvc.saveProcurementPlanDetails(u).success(function() { r.aresNotification.success("保存成功");
                r.getPreHandleSuppliers().then(function() { var n = _.find(r.$scope.suppliers, function(n) { return n.id === r.$scope.selectedSupplier.id });
                    n || (r.$scope.selectedSupplier = angular.copy(r.$scope.suppliers[0]));
                    r.search() }) }) }, n.prototype.createProcurementOrder = function() { var n = this,
                t, i; if (this.$scope.uiState.isEdit) return this.aresNotification.error("请先保存修改"); if (t = [], this.$scope.groupedData.forEach(function(i) { var r = i.products[0].applyItems[0],
                        f = [],
                        u = [],
                        e;
                    i.products.forEach(function(n) { n.visible && n.checked && (n.applyItems.forEach(function(n) { f.push({ applyOrderId: n.applyOrderId, applyOrderNo: n.applyOrderNo, applyOrderItemId: n.applyOrderItemId, productId: n.productId, count: n.count }) }), u.push({ productId: n.productId, number: n.count, price: n.price, isNotAgreedProduct: n.isNotAgreedProduct, code: n.code, name: n.name, specification: n.specification, unit: n.unit, producer: n.producer, notes: "" })) });
                    u.length > 0 && (e = { orderDate: moment().format("YYYY-MM-DD"), supplierId: r.supplierId, supplier: r.supplier, officeId: r.officeId, officeName: r.officeName, status: n.enums.ProcurementPayOrderStatus.PreCommit, checkStatus: n.enums.ProcurementPayOrderCheckStatus.PreSubmit, isSyncToDealer: !1, isPushOrder: n.$scope.selectedSupplier.type > 0, purchaserId: 0, purchaserName: "", source: n.enums.ProcurementPayOrderSource.PurchaseApplyForSupplier, procurementOrders: [{ couponAmount: 0, freight: 0, procurementOrderItems: u, totalAmount: 0, paymentAmount: 0 }], notes: "", actualAmount: 0, paymentAmount: 0, applyOrderItems: f }, t.push(e)) }), t.length === 0) { this.aresNotification.error("请选择物品"); return } if (_.any(t, function(n) { return _.any(n.procurementOrders[0].procurementOrderItems, function(n) { return n.number === 0 }) })) { this.aresNotification.error("采购数量不能为0"); return } i = this.aresModalShelf.open({ title: "新增采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-group-supplier-edit-modal-view><\/procurement-order-group-supplier-edit-modal-view>", controller: "ProcurementOrderGroupSupplierEditModalCtrl", resolve: { host: function() { return { payOrders: t, supplier: n.$scope.selectedSupplier } } } });
            i.result.then(function(t) { n.onSupplierIdChange().then(function() { n.$scope.uiState.visibleProductCount === 0 && n.getPreHandleSuppliers().then(function() { n.$scope.selectedSupplier.id = n.$scope.suppliers[0].id;
                        n.onSupplierIdChange() }) });
                n.$scope.selectedSupplier.type > 0 && t && n.openMallCartSlideModal(t) }) }, n.prototype.openMallCartSlideModal = function(n) { this.aresSlidePanel.open("<procurement-order-mall-cart-view><\/procurement-order-mall-cart-view>", "ProcurementOrderMallCartCtrl", { dataHost: function() { return { payOrderNo: n.split(":")[0], ownerOfficeId: n.split(":")[1] } } }, this.$scope) }, n.prototype.exportExcel = function() { var s = this.excelExportUtil.generateColumnSettings,
                r = this.excelExportUtil.Row,
                n = this.excelExportUtil.HeaderCell,
                t = this.excelExportUtil.RegularCell,
                f = this.excelExportUtil.NumberCell,
                u = this.excelExportUtil.PriceCell,
                h = s([75, 150, 75, 150, 75, 75, 75, 75]),
                i = [],
                e, o;
            i.push(new r([new n("供应商：", 2), new t(this.$scope.selectedSupplier.name, 6)]));
            i.push(new r([new n("序号"), new n("名称"), new n("品牌"), new n("规格"), new n("单位"), new n("数量"), new n("报价"), new n("总额")]));
            _.each(this.$scope.groupedData, function(e) { i.push(new r([new n("下单机构：" + e.officeName, 6)])); var o = 0,
                    s = 0;
                _.each(e.products, function(n, e) { var h = parseFloat((n.count * n.price).toFixed(2));
                    i.push(new r([new t(e + 1), new t(n.name), new t(n.producer), new t(n.specification), new t(n.unit), new f(n.count), new u(n.price), new u(h)]));
                    o += n.count;
                    s += h });
                i.push(new r([new n("合计", 5), new f(o), new t(""), new u(s)]));
                i.push(new r([new t("", 8)])) });
            e = { sheets: [{ title: "供应商汇总下单-" + this.$scope.selectedSupplier.name, columns: h, rows: i }] };
            o = new kendo.ooxml.Workbook(e);
            kendo.saveAs({ dataURI: o.toDataURL(), fileName: "供应商汇总下单-" + this.$scope.selectedSupplier.name + ".xlsx" }) }, n.$inject = ["$scope", "officeSvc", "officeSelectorUtil", "$q", "loginContext", "eventAggregator", "aresModalShelf", "procurementApplyOrderSvc", "$timeout", "aresNotification", "inventoryUtil", "enums", "organizationSvc", "aresSlidePanel", "excelExportUtil"], n }();
    supplychainModule.controller("InventoryGroupProcurementSupplierCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryMgmtHomeView", ["$log", function() { "use strict"; return { restrict: "E", templateUrl: "/app/supplychain/views/home/inventory-mgmt-home-view.html", link: function(n) {
            (function() { n.isAres3 = window.Ares3 })() } } }]);
supplychainModule.directive("inventoryProductBrowseHomeView", ["$log", "$timeout", "$q", "$state", "appNav", "permissionProvider", "reportSvc", "eventAggregator", "dataDicSvc", "moduleOptionProvider", function(n, t, i, r, u) { "use strict"; return { restrict: "E", templateUrl: "/app/supplychain/views/home/inventory-product-browse-home-view.html", link: function(n) { var t = function(t) { n.activeMenu = t;
                u.switchState(t, {}) };
            (function() { n.switchPage = t;
                n.isAres3 = window.Ares3;
                t("supplychain.inventory.manage.currently") })() } } }]);
var criticalProductTraceability;
(function() { "use strict"; var n = function() {
        function n(n, t, i) { var r = this;
            this.$q = n;
            this.$timeout = t;
            this.$window = i;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/inventory/critical-product-traceability-view.html";
            this.controller = "CriticalProductTraceabilityCtrl";
            this.link = function(n, t) { var i = r,
                    e = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } },
                    o = function() { u(); var n = angular.element(i.$window);
                        n.on("resize", function() { u() }) },
                    u = function() { var r = angular.element(i.$window).height(),
                            u = r - 234,
                            n = t.find(".table-main");
                        n.height(u);
                        n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(e);
                        t.find("[data-toggle=tooltip]").tooltip() },
                    f = function() { n.unicode ? n.searchCriticalProduct().then(function() { i.$timeout(function() { u() }) }) : (n.criticalProductTraceabilityDto = null, n.isShow = !0) },
                    s = function(n) { var t = window.event ? n.keyCode : n.which;
                        t === 13 && f() };
                (function() { n.isShow = !1;
                    n.unicode = "";
                    n.onEnter = s;
                    n.onUnicodeSearch = f;
                    o() })() } } return n.$inject = ["$q", "$timeout", "$window"], n }();
    systemToolModule.directive("criticalProductTraceabilityView", Ares.tsDirective(n)) })(criticalProductTraceability || (criticalProductTraceability = {}));
supplychainModule.directive("inventoryCurrentlyListView", ["$log", "$q", "$timeout", "$window", "eventAggregator", "$modal", "dataDicSvc", "inventoryProductSvc", "organizationSvc", "gridOptionUtil", "moduleOptionProvider", "inventoryUtil", "loginContext", "aresNotification", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { return { restrict: "E", templateUrl: "/app/supplychain/views/inventory/inventory-currently-list-view.html", controller: "InventoryCurrentlyListCtrl", link: function(n, t) { var c = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } },
                w = function() { e(); var n = angular.element(r);
                    t.find(".list-tabel-wrap .table-main").mCustomScrollbar(c);
                    n.on("resize", function() { e() }) },
                e = function() { var r = t.find(".inventory-currently-list"),
                        i = t.find(".inventory-product-browse"),
                        u = t.find(".inventory-grid"),
                        f = r.height() - i.height() - parseInt(i.css("margin-top")) - parseInt(i.css("margin-bottom")),
                        n;
                    u.height(f);
                    n = t.find(".list-tabel-wrap .table-main");
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(c);
                    ot() },
                b = function(n, t) { var i = n.productId || n.product.id;
                    u.publish(u.events.ProductSelected, i, t.currentTarget) },
                k = function(n) { n.isShowBatches = !n.isShowBatches;
                    i(function() { e() }) },
                h = function(t, r, u) { r || (n.isExpandAll = !n.isExpandAll);
                    y(t);
                    u && u.isShowBatches && y(t, u);
                    i(function() { e() }) },
                y = function(t, i) { var r = t.items;
                    r && r.length > 0 && angular.forEach(r, function(t) { var r = p(t);
                        t.isShowBatches = i && t.id == i.id ? i.isShowBatches && r : n.isExpandAll && r }) },
                p = function(n) { return _.find(n.batches, function(n) { return n.batchNumber || n.expiredDate }) },
                d = function(t) { n.selCategory = t;
                    n.selCategoryId = t ? t.id : 0;
                    n.selCategoriesIds = l.getAllSubCategoriesIds(t);
                    s() },
                g = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && s() },
                nt = function(t) { t == 1 ? n.searchCriteria.productIds = n.procurementPlanProductIds : t == 2 && (n.searchCriteria.productIds = n.expiratingProductIds);
                    n.warningType == t ? (n.warningType = 0, n.searchCriteria.productIds = []) : n.warningType = t;
                    s() },
                tt = function() { var t = [{ field: "name", hidden: !1, title: "名称", width: "250px" }, { field: "producer", hidden: !1, title: "品牌", width: "150px" }, { field: "category", hidden: !1, title: "所属类目", width: "150px" }, { field: "specification", hidden: !1, title: "规格", width: "150px" }, { field: "unit", hidden: !1, title: "单位", width: "150px" }, { field: "code", hidden: !1, title: "内部编码", width: "150px" }, { field: "warehouseName", hidden: !1, title: "仓库", width: "150px" }, { field: "count", hidden: !1, title: "库存数", width: "150px" }, { field: "price", hidden: !1, title: "成本均价", width: "150px" }, { field: "amount", hidden: !1, title: "金额", width: "150px" }, { field: "batchNumber", hidden: !1, title: "批号", width: "150px" }, { field: "expiredDate", hidden: !1, title: "有效期", width: "150px" }, { field: "unicode", hidden: !1, title: "唯一码", width: "300px" }, { field: "isCritical", hidden: !1, title: "高值耗材", width: "150px" }],
                        i, r;
                    n.productCodeOptions.allowInsideCode || (t = _.filter(t, function(n) { return n.field != "code" }));
                    n.isInventoryCostVisible || (t = _.filter(t, function(n) { return n.field != "price" && n.field != "amount" }));
                    n.isProductUnicodeManagementEnabled || (t = _.filter(t, function(n) { return n.field != "unicode" }));
                    i = n.initSearchCriteria();
                    n.warningType > 0 && (i.isOnlyShowCountWarn = !0, n.warningType == 2 && (i.isOnlyShowExpiratingWarn = !0));
                    r = { criteria: i, columns: t };
                    o.exportProductBatch(r) },
                it = function(t, i) { var r = f.open({ animation: !0, backdrop: "static", template: "<inventory-product-unpack-view><\/inventory-product-unpack-view>", controller: "InventoryProductUnpackCtrl", backdropClass: "inventory-modal-backdrop", windowClass: "inventory-product-unpack-modal-wrapper", resolve: { host: function() { return { currentInventoryItem: t, batchIndex: i } } } });
                    r.result.then(function(t) { t && n.search() }) },
                rt = function(t, i) { var r = _.filter(n.productPackages, function(n) { return n.toProductId === t.productId }),
                        e = angular.isDefined(i) ? t.batches[i].count : t.count,
                        u; if (_.every(r, function(n) { return e < n.count })) { v.error("当前库存数量低于最小合包数量，无法合包。"); return } u = f.open({ animation: !0, backdrop: "static", template: "<inventory-product-pack-view><\/inventory-product-pack-view>", controller: "InventoryProductPackCtrl", backdropClass: "inventory-modal-backdrop", windowClass: "inventory-product-pack-modal-wrapper", resolve: { host: function() { return { currentInventoryItem: t, batchIndex: i, packageRules: r } } } });
                    u.result.then(function(t) { t && n.search() }) },
                ut = function(t, i) { var r = { name: t.product.name, warehouseName: t.warehouseName, specification: t.product.specification, inventoryCount: i.count, checkerId: a.providerId, warehouseId: t.warehouseId, notes: "", items: [{ productId: t.productId, actualCount: "", details: [{ batchNumber: i.batchNumber, expiredDate: i.expiredDate, unicode: i.unicode, actualCount: "", notes: "" }] }] },
                        u = f.open({ animation: !0, backdrop: "static", template: "<inventory-product-check-edit-view><\/inventory-product-check-edit-view>", controller: "InventoryProductCheckEditCtrl", windowClass: "simple-modal inventory-product-check-model-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { inventoryCheckOrder: r } } } });
                    u.result.then(function() { s(t, 1, n.searchCriteria.pageIndex) }) },
                s = function(t, i, r) { n.search(r).then(function() { n.isExpandAll = !1;
                        i = i ? i : 0;
                        h(n.currentInventoryList, i, t) }) },
                ft = function(t) { n.searchSelectedProduct = t;
                    s() },
                et = angular.element(r).height() - 230,
                ot = function() { i(function() { t.find(".list-tabel-wrap").find('[data-toggle="tooltip"]').tooltip() }) },
                st = function(t) { n.search(t).then(function() { h(n.currentInventoryList, 1) }) },
                ht = function(t) { n.searchCriteria.sortField === t ? n.searchCriteria.sortDirection === 0 ? n.searchCriteria.sortDirection = 1 : n.searchCriteria.sortDirection === 1 && (n.searchCriteria.sortField = null, n.searchCriteria.sortDirection = null) : (n.searchCriteria.sortField = t, n.searchCriteria.sortDirection = 0);
                    n.search() },
                ct = function() { n.searchMode = !n.searchMode;
                    i(function() { e() }) };
            (function() { n.onSelectProduct = b;
                n.currentBatchesChange = k;
                n.expandAllChange = h;
                n.checkBatches = p;
                n.initTableView = e;
                n.onProductCategoryChange = d;
                n.onEnter = g;
                n.warningChange = nt;
                n.exportInventoryProduct = tt;
                n.productUnpack = it;
                n.productPack = rt;
                n.productCheck = ut;
                n.searchAndOpen = s;
                n.onProductSelected = ft;
                n.categorySelectHeight = et;
                n.pageSearch = st;
                n.sortTable = ht;
                n.switchMode = ct;
                w() })() } } }]);
supplychainModule.directive("inventoryOutOrderCountDialogView", ["$log", "$modal", "$timeout", "loginContext", function(n, t, i) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/inventory/inventory-out-order-count-dialog-view.html", link: function(n, t) { var r = function(i, r) { if (r.keyCode === 13) { var u = t.find(".table-main input");
                        u.length === i && (n.save(), i = 0);
                        u[i].focus() } },
                u = function() { var n = t.find(".table-main input");
                    n && n[0] && n[0].focus() };
            (function() { n.changeEnter = r;
                i(function() { Ares.centerModal(t.closest(".modal-dialog"));
                    u() }, 5) })() } } }]);
supplychainModule.directive("inventoryProductWarehouseDetailView", ["$log", "$q", "$timeout", "$window", "$modal", "aresSlidePanel", "aresNotification", "eventAggregator", "$rootScope", "dataDicSvc", "inventorySvc", "warehouseSvc", "gridOptionUtil", "practiceSvc", "loginContext", "moduleOptionProvider", "inventoryUtil", "aresTreeViewUtil", "aresModalShelf", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k) { return { restrict: "E", templateUrl: "/app/supplychain/views/inventory/inventory-product-warehouse-detail-view.html", controller: "InventoryProductWarehouseDetailViewCtrl", link: function(n, u) { var f = null,
                p = 0,
                lt = [{ isHidden: !1, field: "code", title: "内部编码", width: "180px", editable: !1, locked: !0 }, { template: "<div class='double-line-text' title='#: name #'><a data-product-id='#: productId #'>#: name #<\/a><\/div>", field: "name", title: "名称", headerAttributes: { "class": "cell-left", style: "text-align:center!important" }, attributes: { "class": "cell-left" }, width: "180px", editable: !1, locked: !0 }, { isHidden: !1, field: "producer", title: "品牌", headerAttributes: { "class": "cell-left" }, attributes: { "class": "cell-left" }, width: "180px" }, { isHidden: !1, field: "specification", title: "规格", headerAttributes: { "class": "cell-left" }, attributes: { "class": "cell-left" }, width: "180px", template: "<div class='double-line-text' title='#: specification #'>#: specification #<\/div>" }, { isHidden: !1, field: "unit", title: "单位", width: "120px" }, { isHidden: !1, field: "categoriesTemplate", title: "所属类目", width: "200px" }, { isHidden: !1, field: "batchCount", title: "合计变更数量", width: "130px" }, { isHidden: !1, field: "batchAmount", title: "合计变更总额", width: "130px", format: "{0:n}", headerAttributes: { "class": "cell-right" }, attributes: { "class": "cell-right" } }],
                at = angular.element(r);
            at.on("resize", function() { nt(!0) }); var ut = function(t) { n.showSummaryColumns = t },
                vt = function() { var r = t.defer(),
                        i = angular.copy(lt); return n.productCodeOptions.allowInsideCode || (i = _.filter(i, function(n) { return n.title !== "内部编码" })), n.showSummaryColumns && angular.forEach(i, function(t) { var i = _.find(n.showSummaryColumns, function(n) { return n == t.field });
                        t.hidden = i ? !1 : !0 }), r.resolve(i), r.promise },
                ft = function() { vt().then(function(t) { a.formatColumns(t, n.showSummaryColumns);
                        u.find("#inventoryInOutDetailGrid").html(""); var i = u.find("#inventoryInOutDetailGrid");
                        nt();
                        f = u.find("#inventoryInOutDetailGrid").kendoGrid({ dataSource: { transport: { read: function(t) { n.pageIndex = t.data.page || 1;
                                        n.pageSize = t.data.pageSize || 15;
                                        t.data.sort && t.data.sort.length > 0 ? (n.sortField = t.data.sort[0].field, n.sortDirection = t.data.sort[0].dir == "asc" ? 0 : 1) : (n.sortField = null, n.sortDirection = null);
                                        t.data.pageSize ? n.onPageChangedSummary().then(function(n) { t.success(n) }) : t.success({ totalCount: 0, itemList: [] }) } }, schema: { data: "itemList", total: "totalCount" }, pageSize: n.pageSize, serverPaging: !0, serverSorting: !0, serverFiltering: !0 }, resizable: !0, columnResizeHandleWidth: 20, reorderable: !0, sortable: !1, height: p, columns: t, columnMenu: !0, dataBound: yt, columnMenuInit: function(n) { $(n.container).find(".k-sort-asc").remove();
                                $(n.container).find(".k-sort-desc").remove() }, columnShow: function(n) { var t = n.sender.columns;
                                a.updateColumnsOption(a.keys.inventoryOrderItemSummaryGridOption, t, ut);
                                Ares.DockGridColMenuPos(n.sender) }, columnHide: function(n) { var t = n.sender.columns;
                                a.updateColumnsOption(a.keys.inventoryOrderItemSummaryGridOption, t, ut);
                                Ares.DockGridColMenuPos(n.sender) } }).data("kendoGrid") }) },
                et = function() { n.showSummaryColumns ? ft() : n.loadColumnsOptionSummary().then(function() { ft() }) },
                yt = function(n) { Ares.DockGridColMenuPos(n.sender); var t = this.dataSource.data();
                    $(u).find("#inventoryInOutDetailGrid tbody tr td a").each(function() { $(this).bind("click", function(n) { var t = $(this).attr("data-product-id");
                            t && ot(t, n) }) }) },
                d = null,
                pt = [{ template: "<div class='double-line-text' title='#: orderNumber #'><a data-order-id ='#: orderId #' data-inventory-type ='#: inventoryType #'>#: orderNumber #<\/a><\/div>", field: "orderNumber", title: "<span class='first-column-text'>单据号<\/span>", attributes: { "class": "cell-left" }, width: "150px", editable: !1, headerAttributes: { "class": "cell-left", style: "min-width:150px" } }, { isHidden: !1, field: "actionStr", title: "类型", width: "150px" }, { isHidden: !1, field: "orderDate", title: "单据日期", width: "200px" }, { isHidden: !1, field: "warehouseName", title: "仓库", width: "150px" }, { isHidden: !1, field: "code", title: "内部编码", width: "150px" }, { template: "<div class='double-line-text' title='#: name #'><a data-product-id='#: productId #'>#: name #<\/a><\/div>", field: "name", title: "名称", headerAttributes: { "class": "cell-left" }, attributes: { "class": "cell-left" }, width: "150px", editable: !1 }, { isHidden: !1, field: "producer", title: "品牌", headerAttributes: { "class": "cell-left" }, attributes: { "class": "cell-left" }, width: "150px" }, { isHidden: !1, field: "categoriesTemplate", title: "所属类目", width: "200px" }, { isHidden: !1, field: "specification", title: "规格", headerAttributes: { "class": "cell-left" }, attributes: { "class": "cell-left" }, width: "150px", template: "<div class='double-line-text' title='#: specification #'>#: specification #<\/div>" }, { isHidden: !1, field: "unit", title: "单位", width: "100px" }, { isHidden: !0, field: "producerCompany", title: "生产企业", width: "150px" }, { isHidden: !0, field: "factoryLocation", title: "产地", width: "150px" }, { isHidden: !0, field: "sfdaCode", title: "药(械)准字", width: "150px" }, { isHidden: !0, field: "isCritical", title: "高值耗材", width: "150px", template: "# if(isCritical) {#是#} else {#否#} #" }, { isHidden: !1, field: "freeField1", title: "自由项1", width: "150px" }, { isHidden: !1, field: "freeField2", title: "自由项2", width: "150px" }, { isHidden: !1, field: "freeField3", title: "自由项3", width: "150px" }, { isHidden: !1, field: "referenceOrderNo", title: "业务单号", width: "180px" }, { isHidden: !1, field: "batchNumber", title: "批号", width: "150px" }, { isHidden: !1, field: "expiredDate", title: "有效期", width: "150px" }, { isHidden: !1, field: "unicode", title: "唯一码", width: "300px" }, { isHidden: !1, field: "batchCount", title: "变更数量", width: "100px", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "bussinessPrice", title: "业务单价", width: "100px", format: "{0:n}", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "businessAmount", title: "业务总额", width: "100px", format: "{0:n}", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "batchPrice", title: "成本均价", width: "100px", format: "{0:n}", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "batchAmount", title: "成本总额", width: "100px", format: "{0:n}", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "afterCount", title: "结存数量", width: "100px", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "afterPrice", title: "结存均价", width: "100px", format: "{0:n}", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "afterAmount", title: "结存总额", width: "100px", format: "{0:n}", attributes: { "class": "cell-right" } }, { isHidden: !1, field: "dealer", title: "供应商", width: "150px" }, { isHidden: !1, field: "consigneeStr", title: "收退货单位", width: "150px" }, { isHidden: !1, field: "senderOrReceiver", title: "经办人", width: "150px" }, { isHidden: !1, field: "operator", title: "制单人", width: "150px" }, { isHidden: !1, field: "recordCreatedTime", title: "制单时间", width: "150px" }, { isHidden: !1, field: "itemNotes", title: "备注", width: "150px" }, { isHidden: !1, field: "notes", title: "整单备注", width: "150px" }, ],
                wt = function() { w.getProductCategories().then(function(t) { n.selCategoryId = 0;
                        n.selCategory = { name: "全部分类", id: 0 };
                        n.categoriesTree = b.unflatten(t, "showOrder");
                        n.categoriesTree.splice(0, 0, n.selCategory) }) },
                ot = function(n, t) { o.publish(o.events.ProductSelected, n, t.delegateTarget) },
                bi = function() { var i = t.defer(); return h.warehouseDic.loadActive().then(function(t) { n.warehouses = t;
                        i.resolve(!0) }), i.promise },
                bt = function(n) { Ares.DockGridColMenuPos(n.sender); var t = this.dataSource.data();
                    $(u).find("#inventoryInOutDetailGrid tbody tr td a").each(function() { $(this).bind("click", function(n) { var u = $(this).attr("data-product-id"),
                                t, i, r;
                            u ? ot(u, n) : (t = $(this).attr("data-order-id"), i = $(this).attr("data-inventory-type"), t && i && (r = { id: t }, i == "In" ? kt(r) : dt(r))) }) }) },
                kt = function(t) { var i = k.open({ template: "<inventory-in-warehouse-order-list-view><\/inventory-in-warehouse-order-list-view>", controller: "inventoryInWarehouseOrderListCtrl", title: "入库信息", titleIconClass: "iconfont icon-ruku1", resolve: { dataHost: function() { return { inOrder: t } } }, needActive: !0 });
                    i.result.then(function() { n.refreshGrid() }) },
                dt = function(t) { var i = k.open({ template: "<inventory-out-warehouse-order-list-view><\/inventory-out-warehouse-order-list-view>", controller: "inventoryOutWarehouseOrderListCtrl", title: "出库信息", titleIconClass: "iconfont icon-ruku1", resolve: { dataHost: function() { return { outOrder: t } } }, needActive: !0 });
                    i.result.then(function() { n.refreshGrid() }) },
                gt = function(t) { t.warehouseId = s.currentWarehouseId != 0 ? s.currentWarehouseId : null;
                    t.categoriesIds = n.selCategoriesIds; var i = moment(t.startDate).format("YYYY-MM-DD"),
                        r = moment(t.endDate).add(1, "days").format("YYYY-MM-DD");
                    t.startDate = i;
                    t.endDate = r;
                    t.inoutType = 0;
                    t.operatorId = n.searchCriteria.operatorId > 0 ? n.searchCriteria.operatorId : null;
                    t.receiverOrSenderId = n.searchCriteria.receiverOrSenderId > 0 ? n.searchCriteria.receiverOrSenderId : null;
                    t.dealer = n.searchCriteria.dealer == "所属供应商" ? null : n.searchCriteria.dealer;
                    t.consigneeType = n.searchCriteria.consigneeType == "all" ? null : n.searchCriteria.consigneeType;
                    t.action = n.searchCriteria.action == "all" ? null : n.searchCriteria.action;
                    t.consignee = n.searchCriteria.consignee == "all" || n.searchCriteria.consignee == "全部" || n.searchCriteria.consignee == "全部员工" || n.searchCriteria.consignee == "全部科室" || n.searchCriteria.consignee == "全部诊室" ? null : n.searchCriteria.consignee;
                    t.consignmentDealerId = n.searchCriteria.consignmentDealerId > 0 ? n.searchCriteria.consignmentDealerId : null;
                    t.action == "allIn" ? (t.inoutType = 1, t.action = null) : t.action == "allOut" && (t.inoutType = 2, t.action = null);
                    n.searchSelectedProduct ? n.searchSelectedProduct.products ? t.productIds = _.pluck(n.searchSelectedProduct.products, "id") : t.productId = n.searchSelectedProduct.id : t.productId = null },
                rt = function() { n.showColumns ? st() : n.loadColumnsOption().then(function() { st() }) },
                nt = function(n) { var r = u.find(".inventory-product-warehouse-detail"),
                        i = u.find(".inventory-product-browse"),
                        e = u.find(".inventory-grid"),
                        t = u.find(".table-footer");
                    girdHeight = r.height() - i.height() - parseInt(i.css("margin-top")) - parseInt(i.css("margin-bottom"));
                    e.height(girdHeight);
                    p = girdHeight - t.height() - parseInt(t.css("margin-top")) - parseInt(t.css("margin-bottom")) - parseInt(t.css("padding-top")) - parseInt(t.css("padding-bottom"));
                    n && (d && d.content && (d.content.height(p - 33), d.content.closest(".k-grid").height(p)), f && f.content && (f.content.height(p - 33), f.content.find("table").height() > f.content.height() ? f.content.siblings(".k-grid-content-locked").height(p - 43) : f.content.siblings(".k-grid-content-locked").height(p - 33), f.content.closest(".k-grid").height(p))) },
                st = function() { ni().then(function(t) { tt(t);
                        a.formatColumns(t, n.showColumns); var r = u.find("#inventoryInOutDetailGrid");
                        r.html("");
                        i(function() { nt();
                            d = r.kendoGrid({ dataSource: { transport: { read: function(t) { n.pageIndex = t.data.page || 1;
                                            n.pageSize = t.data.pageSize || 15;
                                            t.data.sort && t.data.sort.length > 0 ? (n.sortField = t.data.sort[0].field, n.sortDirection = t.data.sort[0].dir === "asc" ? 0 : 1) : (n.sortField = null, n.sortDirection = null);
                                            t.data.pageSize ? n.onPageChanged().then(function(n) { t.success(n) }) : t.success({ totalCount: 0, itemList: [] }) } }, schema: { data: "itemList", total: "totalCount" }, pageSize: n.pageSize, serverPaging: !0, serverSorting: !0, serverFiltering: !0 }, resizable: !0, columnResizeHandleWidth: 20, reorderable: !0, sortable: !1, height: p, columns: t, columnMenu: !0, dataBound: bt, columnMenuInit: function(n) { $(n.container).find(".k-sort-asc").remove();
                                    $(n.container).find(".k-sort-desc").remove() }, columnShow: function(n) { var t = n.sender.columns;
                                    tt(t);
                                    a.updateColumnsOption(a.keys.inventoryOrderItemGridOption, t, ht);
                                    Ares.DockGridColMenuPos(n.sender) }, columnHide: function(n) { var t = n.sender.columns;
                                    tt(t);
                                    a.updateColumnsOption(a.keys.inventoryOrderItemGridOption, t, ht);
                                    Ares.DockGridColMenuPos(n.sender) } }).data("kendoGrid") }) }) },
                ni = function() { var r = t.defer(),
                        i = angular.copy(pt),
                        u, f, e; return n.productCodeOptions.allowInsideCode || (i = _.filter(i, function(n) { return n.title !== "内部编码" })), n.isProductUnicodeManagementEnabled || (i = _.filter(i, function(n) { return n.title !== "唯一码" })), n.showColumns && angular.forEach(i, function(t) { var i = _.find(n.showColumns, function(n) { return n == t.field });
                        t.hidden = i ? !1 : !0 }), n.freeField1 ? (u = _.find(i, function(n) { return n.field == "freeField1" }), u.title = n.freeField1.itemValue) : i = _.filter(i, function(n) { return n.field != "freeField1" }), n.freeField2 ? (f = _.find(i, function(n) { return n.field == "freeField2" }), f.title = n.freeField2.itemValue) : i = _.filter(i, function(n) { return n.field != "freeField2" }), n.freeField3 ? (e = _.find(i, function(n) { return n.field == "freeField3" }), e.title = n.freeField3.itemValue) : i = _.filter(i, function(n) { return n.field != "freeField3" }), r.resolve(i), r.promise },
                tt = function(t) { var i = _.find(t, function(n) { return n.field == "amount" && !n.hidden });
                    n.isShowTotal = i ? !0 : !1 },
                ht = function(t) { n.showColumns = t },
                g = function() { if (n.isProductSummary) f ? f.dataSource.page(1) : et();
                    else if (d) d.dataSource.page(1);
                    else rt() },
                ct = function() { var f = n.inventoryProductList && n.inventoryProductList.totalCount > n.maxExportInventoryRowCount ? !0 : !1,
                        t, i, r, u;
                    f ? n.createInventoryOrderItemBackgroundReport() : d && (t = angular.copy(d.columns), i = _.find(t, function(n) { return n.field == "orderNumber" }), i && (i.title = "单据号"), r = angular.copy(n.searchCriteria), n.setSearchCriteria(r), u = { criteria: r, columns: t }, c.exportInventoryOrderItem(u)) },
                ti = function() { var i, t, r;
                    f && (i = angular.copy(f.columns), t = angular.copy(n.searchCriteria), n.setSearchCriteria(t), r = { criteria: t, columns: i }, c.exportInventoryOrderItemSummary(r)) },
                ii = function() { n.isProductSummary ? ti() : ct() },
                ri = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && g() },
                ki = function(t) { var i = n.searchCriteria,
                        o = t.sender.value(),
                        s = moment(o).startOf("day"),
                        r = moment(i.startDate).startOf("day"),
                        f = moment(i.endDate).startOf("day"),
                        u; if (r.diff(s) && (i.startDate = r.toDate()), r.isAfter(f)) { u = f.toDate();
                        t.sender.value(u);
                        i.startDate = u;
                        e.error("起始时间不能大于截止时间");
                        n.refreshGrid(); return } n.refreshGrid() },
                di = function(t) { var i = n.searchCriteria,
                        o = t.sender.value(),
                        s = moment(o).startOf("day"),
                        f = moment(i.startDate).startOf("day"),
                        r = moment(i.endDate).startOf("day"),
                        u; if (r.diff(s) && (i.endDate = r.toDate()), f.isAfter(r)) { u = f.toDate();
                        t.sender.value(u);
                        i.endDate = u;
                        e.error("截止时间不能小于起始时间");
                        n.refreshGrid(); return } n.refreshGrid() },
                ui = function() { n.searchMode = !n.searchMode;
                    i(function() { nt(!0) }) },
                fi = function() { var i = []; return i.push(h.dealerDic.loadActive().then(function(t) { n.dealers = t;
                        n.dealers.splice(0, 0, { name: "所属供应商" });
                        n.searchCriteria.dealer = "所属供应商" })), n.isConsignmentModeEnabled && i.push(l.getDealerWarehouseList().then(function(t) { t && t.data && (n.dealerWarehouses = angular.copy(t.data), n.dealerWarehouses.splice(0, 0, { dealerId: 0, dealerName: "所属寄售供应商" })) })), t.all(i) },
                ei = function(t) { var i = t.sender.value();
                    n.searchCriteria.consigneeType = i;
                    n.searchCriteria.consignee = "all";
                    n.providerSelectInstance.clear();
                    i == "1" ? oi().then(function(n) { it(n, "全部诊室", "description") }) : i == "2" ? si().then(function(n) { it(n, "全部科室", "itemName") }) : it([{ name: "全部" }], "全部", "name");
                    n.refreshGrid() },
                it = function(t, i, r) { var f = angular.copy(t),
                        e;
                    i == "全部员工" && (e = _.find(f, function(n) { return n.id == 0 }), e || f.splice(0, 0, { id: 0, name: "全部员工" }));
                    u.find("#consignee-drop").kendoDropDownList({ filter: "contains", dataSource: f, dataTextField: r, dataValueField: r, select: function(t) { n.searchCriteria.consignee = this.dataItem(t.item)[this.options.dataValueField] || "all";
                            n.refreshGrid() } }) },
                gi = function() { var i = t.defer(); return n.providers ? i.resolve(n.providers) : i.resolve([]), i.promise },
                oi = function() { var i = t.defer(); return n.operatories ? i.resolve(n.operatories) : h.operatoryDic.load().then(function(t) { t = _.sortBy(t, "id");
                        n.operatories = t;
                        n.operatories.splice(0, 0, { id: 0, description: "全部诊室" });
                        i.resolve(t) }), i.promise },
                si = function() { var i = t.defer(); return n.departments ? i.resolve(n.departments) : v.getDepartment().success(function(t) { n.departments = t;
                        n.departments.splice(0, 0, { id: 0, itemName: "全部科室" });
                        i.resolve(t) }), i.promise },
                hi = function() { var t = u.find("#inventoryInOutDetailGrid");
                    n.isProductSummary ? et() : rt() },
                ci = function(t) { var i = u.find("#inventoryInOutDetailGrid").data("kendoGrid");
                    t === "pageIndex" && i.dataSource.page(n.pageIndex);
                    t === "pageSize" && i.dataSource.pageSize(n.pageSize) },
                li = function(t) { n.selCategory = t;
                    n.selCategoryId = t ? t.id : 0;
                    n.selCategoriesIds = w.getAllSubCategoriesIds(t);
                    g() },
                ai = function() { i(function() { g() }) },
                vi = function() { n.searchCriteria.startDate = n.searchTimeRange.startDate;
                    n.searchCriteria.endDate = n.searchTimeRange.endDate;
                    g() },
                yi = function() { var i = t.defer(); return h.systemItemDic.loadActive().then(function(t) { if (t) { var r = _.filter(t, { itemType: "物品自由项" });
                            r && (n.freeField1 = _.find(r, { itemName: "物品自由项1" }), n.freeField2 = _.find(r, { itemName: "物品自由项2" }), n.freeField3 = _.find(r, { itemName: "物品自由项3" })) } i.resolve(!0) }), i.promise },
                pi = angular.element(r).height() - 230,
                wi = function(t) { n.searchCriteria.consignee = t ? t.name : null;
                    g() };
            (function() { n.onProviderSelected = wi;
                n.providerSelectInstance = null;
                n.isGroup = y.isGroup;
                n.onProductSelected = ai;
                n.refreshGrid = g;
                n.exportExcel = ii;
                n.onEnter = ri;
                n.setSearchCriteria = gt;
                n.updateGrid = hi;
                wt();
                n.isShowTotal = !1;
                n.isProductSummary = !1;
                n.refreshTotalAmount = tt;
                n.switchMode = ui;
                n.exportInventoryOrderItem = ct;
                n.onChangeInventoryConsigneeType = ei;
                n.onPaginationChanged = ci;
                n.onProductCategoryChange = li;
                n.isInventoryCostVisible = y.isInventoryCostAllowed;
                n.initSearchData();
                n.categorySelectHeight = pi;
                n.onSearchTimeRangeChanged = vi;
                n.maxExportInventoryRowCount = 5e3;
                n.initProductCodeOptions().then(function() { yi().then(function() { it([{ name: "全部" }], "全部", "name");
                        rt() }) });
                n.loadProductUnicodeManagementEnabled().then(function() { fi() }) })() } } }]);
supplychainModule.directive("inventoryCheckOrderEditModalView", ["eventAggregator", "$timeout", "$window", "aresConfirmDialog", function(n, t, i, r) { "use strict"; return { templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-check-order-edit-modal/inventory-check-order-edit-modal-view.html", replace: !0, link: function(u, f) { var e = f.find(".table-main-content"),
                s = function() { h();
                    u.initBaseData().then(function() { u.initBusinessData();
                        c() }) },
                h = function() { u.skuAutoCompleteOptions = { mode: "checkOrder", isLinkedCare: null };
                    u.uiState = { currentSkuNotes: "", hasBatchOrExpired: !1, warehouse: { onChange: o, onSelect: l, disabled: !0 } } },
                c = function() { u.currentInventoryCheckOrder.id && u.currentInventoryCheckOrder.id !== 0 || (u.uiState.warehouse.disabled = !1) },
                o = function() { u.$modalInstance.broadcast("WAREHOUSE_ID_CHANGE", { warehouseId: u.currentInventoryCheckOrder.warehouseId }) },
                l = function(n) { var t = n.item.context.innerText,
                        i = _.find(u.baseData.warehouses, { name: t });
                    u.currentInventoryCheckOrder && u.currentInventoryCheckOrder.items && u.currentInventoryCheckOrder.items.length > 0 && (n.preventDefault(), r.confirm({ message: "切换盘点仓库将清空已添加物品列表" }).then(function() { u.currentInventoryCheckOrder.items = [];
                        u.currentInventoryCheckOrder.warehouseId = i.id;
                        o();
                        u.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: [] }) })) },
                a = function(t, i) { var r = t.productId || t.id;
                    n.publish(n.events.ProductSelected, r, i.delegateTarget) },
                v = function(n) { n.actualCount = n.actualCount * 1;
                    _.isNumber(n.actualCount) && !_.isNaN(n.actualCount) ? (n.actualCount = n.actualCount < 0 ? 0 : n.actualCount, n.countGap = n.actualCount - n.inventoryCount) : (n.actualCount = "", n.countGap = "") },
                y = function(n, i) { t(function() { var r, u, o; if (i) r = e.find("tr:first").find("input:first"), r.focus(), r.length && angular.isFunction(r[0].select) && t(function() { r[0].select() }, 0, 50);
                        else { if (!n || n.keyCode !== 13) return; if (u = angular.element(n.target), r = u.closest("td").find("input:last"), r.length > 0 && u[0] !== r[0]) { r.focus();
                                angular.isFunction(u[0].select) && u[0].select(); return } if (r = u.closest("td").nextAll(":not(.disabled):not(.actions-td):first").find("input:first"), r.length > 0) { r.focus();
                                angular.isFunction(u[0].select) && u[0].select(); return } o = f.find(".sku-auto-complete-selector-view").find("input");
                            o.length > 0 && o.focus() } }, 0, !1) },
                p = function() { t(function() { var n = angular.element(i).height() - 210;
                        n -= angular.element(".basic-info-form").height();
                        e.height(n);
                        e.data("mCustomScrollbarIndex") ? e.mCustomScrollbar("update") : e.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } });
                        f.find("[data-toggle=tooltip]").tooltip() }, 100, !1) };
            (function() { u.onSelectedProduct = a;
                u.onCountChanged = v;
                u.focusNextInput = y;
                u.initScrollbar = p;
                s() })() } } }]);
supplychainModule.controller("InventoryCheckOrderEditModalCtrl", ["$log", "$scope", "$modalInstance", "$q", "$document", "aresNotification", "aresConfirmDialog", "inventorySvc", "host", "eventAggregator", "inventoryUtil", "inventoryProductSvc", "dataDicSvc", "$timeout", "loginContext", "warehouseUtil", "$rootScope", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) { "use strict"; var d = function() { return !t.currentInventoryCheckOrder.items || t.currentInventoryCheckOrder.items.length === 0 ? "请添加盘点物品清单" : c.checkOrderDateValid(t.currentInventoryCheckOrder.orderDate) ? c.checkOrderGreaterThanToday(t.currentInventoryCheckOrder.orderDate) ? "单据日期不能大于当前日期 ！" : t.currentInventoryCheckOrder.checkerId <= 0 ? "请选择盘点负责人 ！" : k() : "请输入单据日期 ！" },
        k = function() { var n = 0; return angular.forEach(t.currentInventoryCheckOrder.items, function(t) { n += t.details.length }), n > 200 ? "一次盘点最多只能添加200条盘点明细!" : void 0 },
        ut = function() { var n = angular.copy(t.currentInventoryCheckOrder); return n.orderDate = moment(n.orderDate).format("YYYY-MM-DD"), n.items = [], angular.forEach(t.currentInventoryCheckOrder.items, function(t) { var i = t.details,
                    r = { productId: t.productId, batchNumber: i.length > 1 ? "" : i[0].batchNumber, expiredDate: i.length > 1 ? null : i[0].expiredDate, unicode: i.length > 1 ? "" : i[0].unicode, details: [] },
                    u = 0;
                angular.forEach(i, function(n) { var t = { checkOrderItemId: n.checkOrderItemId, batchNumber: n.batchNumber, expiredDate: n.expiredDate ? moment(n.expiredDate).format("YYYY-MM-DD") : null, unicode: n.unicode, actualCount: n.actualCount, inventoryCount: n.inventoryCount, notes: n.notes };
                    u += n.actualCount;
                    r.details.push(t) });
                r.actualCount = u;
                n.items.push(r) }), n },
        g = function() { var n = r.defer(),
                i = d(),
                u, e; return i ? (f.error(i), n.reject()) : (u = ut(), e = t.currentInventoryCheckOrder.id > 0 ? o.updateCheckOrder : o.addCheckOrder, e(u).success(function(i) { tt(i);
                t.currentInventoryCheckOrder = i;
                n.resolve(!0) }).error(function(t) { c.showInventoryErrorMessage(t, "保存失败");
                n.reject() })), n.promise },
        ft = function() { Ares.ensureNotDuplicated("InventoryCheckOrderSaveCheck") && g().then(function() { f.success("保存成功");
                nt("保存", t.currentInventoryCheckOrder.state === 0);
                i.close(t.currentInventoryCheckOrder) }) },
        et = function() { if (Ares.ensureNotDuplicated("InventoryCheckOrderApproveCheck")) { var n = d(); if (n) { f.error(n); return } e.confirm({ message: "您确定执行该单据吗？单据执行后库存将发生变更" }).then(function() { g().then(function() { ot() }) }) } },
        ot = function() { o.approveCheckOrder(t.currentInventoryCheckOrder.id).success(function() { t.currentInventoryCheckOrder.state = 1;
                f.success("操作成功!");
                nt("保存并执行", !0);
                i.close(t.currentInventoryCheckOrder) }).error(function(n) { c.showInventoryErrorMessage(n, "操作失败") }) },
        nt = function(n, i) { i && h.publish(h.events.RefreshIventoryHint, null, "InventoryCheckEditCtrl");
            t.currentInventoryCheckOrder.id === -1 || t.currentInventoryCheckOrder.id === null || (n = "编辑");
            Ares.sensors.track("InventoryOperation", { OrderNumber: t.currentInventoryCheckOrder.orderNumber, OperationType: "盘点", OperationMode: n }) },
        st = function() { var n = [],
                i; return t.baseData = {}, i = function(n) { return n.splice(0, 0, { id: 0, name: "请选择" }), n }, n.push(a.currentOfficeWorkProviderDic.load().then(function(n) { t.baseData.handlers = i(angular.copy(n)) })), n.push(a.warehouseDic.loadActive().then(function(n) { var i = p.filterWarehouses(n);
                i = _.sortBy(i, function(n) { return !n.isDefault });
                t.baseData.warehouses = i })), r.all(n) },
        ht = function() { var n = r.defer(),
                u = p.getDefaultWarehouse(t.baseData.warehouses).id,
                i; return u = w.currentWarehouseId > 0 ? w.currentWarehouseId : u, i = { state: 0, amount: 0, orderDate: moment(Ares.today()).format("YYYY-MM-DD"), id: s.orderId || 0, checkerId: y.providerId, warehouseId: s.warehouse && s.warehouse.id ? s.warehouse.id : u, items: null }, i.checkerId <= 0 && t.baseData.handlers.length > 1 && (i.checkerId = t.baseData.handlers[1].id), t.currentInventoryCheckOrder = i, s.isCopyToNew && (t.currentInventoryCheckOrder.id = 0), s.orderId > 0 ? o.getCheckOrder(s.orderId).success(function(i) { s.isCopyToNew ? at(i).then(function() { n.resolve(!0) }) : (t.currentInventoryCheckOrder = i, tt(t.currentInventoryCheckOrder), t.initScrollbar(), n.resolve(!0)) }).error(function() { f.error("无法获取订单详情");
                n.reject() }) : n.resolve(!0), n.promise },
        tt = function(n) { angular.forEach(n.items, function(n) { angular.forEach(n.details, function(n) { n.countGap = n.actualCount - n.inventoryCount;
                    (n.expiredDate || n.batchNumber) && (t.uiState.hasBatchOrExpired = !0);
                    n.expiredDate && (n.expiredDate = moment(n.expiredDate).format("YYYY-MM-DD")) }) });
            n.orderDate = moment(n.orderDate).format("YYYY-MM-DD");
            s.checker && (n.checkerId = s.checker.id) },
        b = function(n, r) { var o, u, s, e; if (n) { if (o = function(n) { v(function() { t.currentInventoryCheckOrder.items.splice(0, 0, n);
                            i.broadcast("SKU_SELECT_ADDED", { productId: n.productId });
                            t.initScrollbar();
                            r === "unicode" && f.success("通过扫唯一码添加物品成功");
                            r || v(function() { t.focusNextInput(null, !0) }, 0, !1) }) }, u = angular.copy(n), t.currentInventoryCheckOrder.items = t.currentInventoryCheckOrder.items || [], s = _.find(t.currentInventoryCheckOrder.items, function(n) { return n.productId == u.productId }), s) { f.error("此物品已经在盘点物品列表中！"); return } if (u.details = [], u.batches.length === 0 ? u.details.push({ actualCount: 0, inventoryCount: 0, batchNumber: "", countGap: 0 }) : angular.forEach(u.batches, function(n) { var i = { actualCount: n.count, inventoryCount: n.count, batchNumber: n.batchNumber, unicode: n.unicode, countGap: 0 };
                        n.expiredDate && (i.expiredDate = moment(n.expiredDate).format("YYYY-MM-DD"));
                        (i.expiredDate || i.batchNumber) && (t.uiState.hasBatchOrExpired = !0);
                        u.details.push(i) }), e = 0, angular.forEach(t.currentInventoryCheckOrder.items, function(n) { e += n.details.length }), e + u.details.length > 200) { f.error("一次盘点最多只能添加200条盘点明细!"); return } o(u) } },
        ct = function(n, r) { if (n.details.length > 1) n.details.splice(r, 1);
            else if (n.details.length === 1) { var u = _.findIndex(t.currentInventoryCheckOrder.items, { productId: n.productId });
                t.currentInventoryCheckOrder.items.splice(u, 1) } i.broadcast("SKU_SELECT_REMOVED", { productId: n.productId }) },
        it = function(n) { var i = r.defer(); return l.searchInventoryProductBatch({ productIds: [n.productId], warehouseId: t.currentInventoryCheckOrder.warehouseId }).success(function(t) { n.batches = t;
                i.resolve() }), i.promise },
        rt = function(n) { var i = r.defer(),
                u = _.map(n, function(n) { return n.productId }); return l.searchInventoryProductBatch({ productIds: u, warehouseId: t.currentInventoryCheckOrder.warehouseId }).success(function(t) { var r = _.groupBy(t, "productId");
                _.each(n, function(n) { n.batches = [];
                    r[n.productId] && (n.batches = r[n.productId]) });
                i.resolve() }), i.promise },
        lt = function() { i.on("SKU_SELECT_ADD", function(n) { var t, i; if (n && n.data && (t = n.data.sku, t)) { if (i = k(), i) { f.error(i); return } it(t).then(function() { b(t, !1) }) } });
            i.on("SPU_BATCH_ADD", function(n) { var i, r, t; if (n && n.data && (i = n.data.spus, i)) { if (r = k(), r) { f.error(r); return } t = [];
                    _.each(i, function(n) { _.each(n.products, function(n) { t.push(n) }) });
                    rt(t).then(function() { _.each(t, function(n) { b(n, !1) }) }) } });
            i.on("TAB_SWITCHED", function() { if (t.currentInventoryCheckOrder) { var n = _.pluck(t.currentInventoryCheckOrder.items, "productId");
                    i.broadcast("SKU_EXIST_LIST", { productIds: n }) } }) },
        at = function(n) { t.currentInventoryCheckOrder.warehouseId = n.warehouseId; var i = []; return _.each(n.items, function(n) { n.product.productId = n.product.id;
                i.push(n.product) }), rt(i).then(function() { _.each(i, function(n) { b(n, !1) }) }) };
    (function() { t.removeSkuFromList = ct;
        t.initBusinessData = ht;
        t.saveAndExecute = et;
        t.getSkuBatches = it;
        t.addSkuToList = b;
        t.initBaseData = st;
        t.warehouse = s.warehouse;
        t.save = ft;
        lt() })() }]);
supplychainModule.directive("inventoryInOrderBatchDialogView", ["$log", "$modal", "$timeout", "loginContext", function(n, t, i) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-in-order-batch-dialog/inventory-in-order-batch-dialog-view.html", link: function(n, t) { var r = function(r, u) { if (u.keyCode === 13) { var f = t.find(".table-main input");
                        f.length === r && (n.save(), r = 0);
                        f[r].focus();
                        angular.isFunction(f[r].select) && i(function() { f[r].select() }, 0, 50) } },
                u = function() { var n = t.find(".table-main input");
                    n && n[0] && (n[0].focus(), angular.isFunction(n[0].select) && i(function() { n[0].select() }, 0, 50)) };
            (function() { n.changeEnter = r;
                i(function() { Ares.centerModal(t.closest(".modal-dialog"));
                    u() }, 5) })() } } }]);
supplychainModule.controller("InventoryInOrderBatchDialogCtrl", ["$q", "$scope", "$modalInstance", "host", "aresNotification", function(n, t, i, r, u) { "use strict"; var o = function() { i.close(!1) },
        f = function(n) { t.isOnlyShow ? n.curCount = n.count : n.curCount > n.count - n.inStorageCount && (n.curCount = n.count - n.inStorageCount);
            e() },
        e = function() { var n = 0;
            angular.forEach(t.orderItem.refOutItems, function(t) { t.curCount = t.curCount * 1 || 0;
                n += t.curCount });
            t.orderItem.curCount = n },
        s = function() { var n; return !t.isAllowExceedInventoryCount && (n = _.find(t.orderItem.refOutItems, function(n) { return n.curCount > n.count }), n) ? "物品【" + t.orderItem.product.name + "】库存数不足！" : t.orderItem.unInStorageNum && t.orderItem.curCount > t.orderItem.unInStorageNum ? "出库数量大于待出库数量，请重新输入出库数量！" : "" },
        h = function() { if (!t.isOnlyShow) { e(); var n = s(); if (n) { u.error(n); return } } i.close(t.orderItem) },
        c = function(n) { if ((n.keyCode === 13 || n.key === "Enter") && t.unicodeSearchKeyword.value) { var i = _.find(t.orderItem.refOutItems, function(n) { return n.unicode === t.unicodeSearchKeyword.value });
                i ? i.curCount === 1 ? u.info("该唯一码对应的批次已添加") : (i.curCount = 1, f(i), u.success("该唯一码批次添加成功")) : u.error("找不到该唯一码对应的批次");
                t.unicodeSearchKeyword.value = "" } };
    (function() { t.close = o;
        t.save = h;
        t.onCountChanged = f;
        t.orderItem = r.orderItem;
        t.isOnlyShow = r.isOnlyShow;
        t.isExpireDateVisible = r.orderItem.refOutItems && r.orderItem.refOutItems.some(function(n) { return n.expiredDate });
        t.isBatchNumberVisible = r.orderItem.refOutItems && r.orderItem.refOutItems.some(function(n) { return n.batchNumber });
        t.isUnicodeVisible = r.orderItem.refOutItems && r.orderItem.refOutItems.some(function(n) { return n.unicode });
        t.onUnicodeSearch = c;
        t.unicodeSearchKeyword = { value: "" } })() }]);
supplychainModule.directive("inventoryInOrderEditModalView", ["enums", "$timeout", "eventAggregator", "aresNotification", "aresConfirmDialog", "loginContext", "permissionProvider", "$modal", function(n, t, i, r, u, f, e, o) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-in-order-edit-modal/inventory-in-order-edit-modal-view.html", link: function(s, h) { var v = function() { s.currentInventoryInOrder.inOrderAction == n.InOrderAction.PurchaseIn || s.currentInventoryInOrder.inOrderAction == n.InOrderAction.ConsignmentIn ? (s.uiState.dealer.visible = !0, s.uiState.deliverType.visible = !1, s.uiState.deliver.visible = !1, s.uiState.patient.visible = !1, s.uiState.returnOrderOffice.visible = !1, s.uiState.priceColumn.title = "入库单价/总额", s.currentInventoryInOrder.dealerId || (s.currentInventoryInOrder.dealerId = 0)) : s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnTakeIn ? (s.uiState.dealer.visible = !1, s.uiState.deliverType.visible = !0, s.uiState.deliverType.disabled = !1, s.uiState.deliverType.label = "退货单位", s.uiState.deliver.visible = !0, s.uiState.deliver.disabled = !1, s.uiState.patient.visible = !1, s.uiState.priceColumn.title = !1, s.uiState.returnOrderOffice.visible = !1, (angular.isUndefined(s.currentInventoryInOrder.deliverType) || _.isNull(s.currentInventoryInOrder.deliverType)) && (s.currentInventoryInOrder.deliverType = "-1"), a()) : s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn ? (s.uiState.dealer.visible = !1, s.uiState.deliverType.visible = !0, s.uiState.deliverType.disabled = !0, s.uiState.deliverType.label = "退货员", s.uiState.deliver.visible = !0, s.uiState.deliver.disabled = !1, s.uiState.patient.visible = !0, s.uiState.priceColumn.title = "退货单价/总额", s.uiState.returnOrderOffice.visible = !1, s.currentInventoryInOrder.deliverType = n.InOrderDeliverType.Provider, a()) : s.currentInventoryInOrder.inOrderAction == n.InOrderAction.NormalIn && (s.uiState.dealer.visible = !1, s.uiState.deliverType.visible = !1, s.uiState.deliver.visible = !1, s.uiState.patient.visible = !1, s.uiState.returnOrderOffice.visible = !1, s.uiState.priceColumn.title = "入库单价/总额");
                    s.uiState.consignmentDealer.visible = s.currentInventoryInOrder.warehouseId == -1 && (s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn || s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnTakeIn) ? !0 : !1;
                    s.skuAutoCompleteOptions.includeZeroCount = s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn || s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnTakeIn;
                    s.skuAutoCompleteOptions.includeZeroCount || _.each(s.currentInventoryInOrder.items, function(n) { _.each(n.batches, function(n) { n.unicode && (n.unicode = "", n.batchNumber = "", n.expiredDate = "") }) });
                    l() },
                a = function() { var i = s.currentInventoryInOrder.deliver;
                    s.currentInventoryInOrder.deliverType === "-1" && (s.deliverDataSource = [{ id: 0, name: "请选择" }]);
                    s.currentInventoryInOrder.deliverType == n.InOrderDeliverType.Provider ? s.deliverDataSource = s.baseData.staffs : s.currentInventoryInOrder.deliverType == n.InOrderDeliverType.Operatory ? s.deliverDataSource = s.baseData.operatories : s.currentInventoryInOrder.deliverType == n.InOrderDeliverType.Department && (s.deliverDataSource = s.baseData.departments);
                    t(function() { var n = _.any(s.deliverDataSource, function(n) { return n.name === i });
                        s.currentInventoryInOrder.deliver = n ? i : "请选择" }) },
                p = function() { s.currentInventoryInOrder.dealerId && s.currentInventoryInOrder.dealerId !== "0" && s.getCurrentDealerPrices().then(function(n) { var t = _.filter(n, function(n) { return n.price > 0 }).length;
                        t && u.warn({ message: '检测到有 <span class="enyo-text-warning-dark">' + t + "<\/span> 个物品在该供应商下有报价，需要更新这些物品的报价吗？", onConfirm: function() { _.each(s.currentInventoryInOrder.items, function(t) { var i = _.find(n, function(n) { return n.productId === t.productId && n.price > 0 });
                                    i && (t.price = i.price.toFixed(2));
                                    s.calcOnCountOrPriceChanged(t) }) }, onCancel: function() {} }) });
                    l() },
                w = function(n, t) { t.batchNumber = n.batchNumber;
                    t.expiredDate = n.expiredDate },
                b = function(n) { n && (s.currentInventoryInOrder.relatedId = n.id, s.currentInventoryInOrder.relatedName = n.name, s.uiState.patient.searchString = n.name) },
                c = h.find(".main-table"),
                k = function() { var t = 265,
                        i;
                    s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn && (t += 50);
                    s.uiState.skuSelector.visible || (t -= 42);
                    i = "calc(100vh - " + t + "px)";
                    c.css({ height: i, maxHeight: i });
                    c.data("mCustomScrollbarIndex") ? c.mCustomScrollbar("update") : c.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) },
                l = function(i) { t(function() { i && (s.uiState.inOrderAction.onChange(), s.uiState.deliverType.visible && s.uiState.deliverType.onChange());
                        h.find("[data-toggle=tooltip]").tooltip();
                        s.uiState.skuSelector.visible = !s.currentInventoryInOrder.referenceOrderId;
                        s.uiState.inOrderAction.disabled = !!s.currentInventoryInOrder.referenceOrderId;
                        s.uiState.inOrderAction.disabled && (s.uiState.inOrderAction.name = _.find(s.baseData.allActionOptions, function(n) { return n.id == s.currentInventoryInOrder.inOrderAction }).name);
                        s.uiState.dealer.disabled = !!s.currentInventoryInOrder.referenceOrderId;
                        s.uiState.deliver.disabled = !!s.currentInventoryInOrder.referenceOrderId && !s.currentInventoryInOrder.hasGroupSalesOrder;
                        s.uiState.patient.visible = s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn && !s.currentInventoryInOrder.hasGroupSalesOrder;
                        s.uiState.patient.disabled = !!s.currentInventoryInOrder.referenceOrderId;
                        s.uiState.returnOrderOffice.visible = !!s.currentInventoryInOrder.referenceOrderId && s.currentInventoryInOrder.hasGroupSalesOrder && s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn;
                        s.currentInventoryInOrder.referenceOrderId && (s.currentInventoryInOrder.inOrderAction == n.InOrderAction.PurchaseIn && !f.isProcurementPriceAllowed || s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn) && (s.uiState.priceColumn.title = !1);
                        s.uiState.batchExpColumn.visible = _.any(s.currentInventoryInOrder.items, function(n) { return n.isBatchNoEnabled || n.isExpiredDateEnabled });
                        s.uiState.batchExpColumn.showDropDownOnly = s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnSalesIn || s.currentInventoryInOrder.inOrderAction == n.InOrderAction.UnTakeIn;
                        s.uiState.syncToDealer.visible = function() { if (!s.currentInventoryInOrder.dealerId || s.currentInventoryInOrder.inOrderAction != n.InOrderAction.PurchaseIn || s.currentInventoryInOrder.referenceOrderId || !s.canCreateSpu || s.isProcurementPriceLockEnabled) return !1; var t = _.find(s.baseData.dealers, function(n) { return n.id == s.currentInventoryInOrder.dealerId }); return t.type == n.OrganizationType.NormalDealer && !s.currentInventoryInOrder.referenceOrderId }();
                        s.uiState.priceColumn.disabled = s.currentInventoryInOrder.referenceOrderId && s.currentInventoryInOrder.inOrderAction == n.InOrderAction.PurchaseIn;
                        s.uiState.orderDate.disabled = s.isCancelAndCopy || !e.isAllowed("inventoryOperation.stockOrderAdditionalRecording");
                        s.uiState.saveOnlyBtn.visible = !s.currentInventoryInOrder.referenceOrderId && !s.isCancelAndCopy; var t = 205,
                            r = 170,
                            u = 370,
                            o = 130,
                            c = 35;
                        s.uiState.batchExpColumn.visible && (t -= 65, r -= 65, u += 130);
                        s.uiState.priceColumn.title || (t += 60, r += 45, o += 50, c += 50, u -= 105);
                        s.uiState.nameColumn.width = t + "px";
                        s.uiState.specColumn.width = r + "px";
                        s.uiState.batchRow.width = u + "px";
                        s.uiState.countColumn.width = o + "px";
                        s.uiState.countColumn.unitWidth = c + "px";
                        k() }) },
                d = function(n, t) { var r = n.productId;
                    i.publish(i.events.ProductSelected, r, t.delegateTarget) },
                g = function(n, i) { t(function() { var r, u, f; if (i) r = c.find("tr:first").find("input[type=text]:first"), r.focus(), angular.isFunction(r[0].select) && t(function() { r[0].select() }, 0, 50);
                        else { if (n && n.keyCode !== 13) return; if (u = angular.element(n.target), r = u.closest("td").find("input:last"), r.length > 0 && u[0] !== r[0]) { r.focus();
                                angular.isFunction(r[0].select) && t(function() { r[0].select() }, 0, 50); return } if (r = u.closest("td").nextAll(":not(.disabled):not(.actions-td):first").find("input:first"), r.length > 0) { r.focus();
                                angular.isFunction(r[0].select) && t(function() { r[0].select() }, 0, 50); return } if (r = u.closest("tr").next().find("input:first"), r.length > 0) { r.focus();
                                angular.isFunction(r[0].select) && t(function() { r[0].select() }, 0, 50); return } f = h.find(".sku-auto-complete-selector-view").find("input");
                            f.focus() } }, 0, !1) },
                nt = function(n) { t(function() { angular.element(n.target).closest("tr").siblings("tr:last").find("input:first").focus() }, 0, !1) },
                tt = function() { var n = null; return c.find("tr").find("input[kendo-date-picker]").each(function() { var t = angular.element(this);
                        t.val() && !t.val().match(/\d{4}-\d{2}-\d{2}/) && (n = t.closest(".product-item-row").find(".product-name").text().trim()) }), n },
                it = function(n) { var t, f; if (Ares.ensureNotDuplicated("SaveInventoryInOrder")) { if (t = s.validateInOrder(n), t) { r.error(t); return } f = function() { s.save(n).then(function(n) { r.success("保存成功");
                                n.state === 0 && i.publish(i.events.RefreshIventoryHint, null, "InventoryInOrderEditCtrl");
                                s.$modalInstance.close(n) }, function(n) { r.error(n) }) };
                        n ? f() : u.warn({ message: "您确定执行该单据吗？单据执行后库存将发生变更", onConfirm: function() { f() }, onCancel: function() {} }) } },
                rt = function(n, t) { var i = angular.element(t.target);
                    i.popover("show");
                    s.uiState.currentPopoverProduct = { skuId: n.productId, spuId: n.productUnityId };
                    s.uiState.currentPopoverAnchor = i },
                ut = function(n) { var t = $(n.target),
                        i = t.data("bs.popover").$tip;
                    i.css("minHeight", "unset") },
                ft = function() { s.uiState.currentPopoverAnchor.popover("hide");
                    s.uiState.currentPopoverAnchor = null; var n = s.$shelfInstance.open({ title: "编辑物品", titleIconClass: "iconfont icon-bianji", template: "<spu-edit-basic-view><\/spu-edit-basic-view>", controller: "SpuEditBasicCtrl", resolve: { host: function() { return { productUnityId: s.uiState.currentPopoverProduct.spuId } } }, confirmClose: !0, needActive: !0 });
                    n.result.then(function(n) { var t = _.find(n.products, function(n) { return n.id === s.uiState.currentPopoverProduct.skuId });
                        t ? _.each(s.currentInventoryInOrder.items, function(n) { n.productUnityId === s.uiState.currentPopoverProduct.spuId && s.reloadSkuToList(n.productId) }) : (s.currentInventoryInOrder.items = _.filter(s.currentInventoryInOrder.items, function(n) { return n.productId !== s.uiState.currentPopoverProduct.skuId }), r.info("当前物品规格已被删除"), s.$modalInstance.broadcast("SKU_SELECT_REMOVED", { productId: s.uiState.currentPopoverProduct.skuId }), s.calcTotalAmount(), s.refreshUi()) }) },
                y = function(t) { var i = t !== n.WarehouseGrade.Consignee.value;
                    s.currentInventoryInOrder.isUnpackingAllowed = i;
                    _.each(s.currentInventoryInOrder.items, function(n) { n.isUnpackingAllowed = i;
                        n.toProductId && i && (n.isPackage = i);
                        s.calcOnAmountChanged(n) }) },
                et = function(t) { var r = this.dataItem(t.item.index()),
                        i, f;
                    s.currentInventoryInOrder.warehouseGrade = r.grade;
                    r.grade === n.WarehouseGrade.Consignee.value ? s.currentInventoryInOrder.referenceOrderId > 0 && s.currentInventoryInOrder.inOrderAction == n.InOrderAction.PurchaseIn ? (t.preventDefault(), u.warn({ message: "下推采购入库不支持寄售仓库" })) : (i = _.filter(s.baseData.inOrderActions, function(t) { return t.id == n.InOrderAction.ConsignmentIn || t.id == n.InOrderAction.UnTakeIn || t.id == n.InOrderAction.UnSalesIn }), i && s.currentInventoryInOrder.inOrderAction != n.InOrderAction.ConsignmentIn && s.currentInventoryInOrder.inOrderAction != n.InOrderAction.UnTakeIn && s.currentInventoryInOrder.inOrderAction != n.InOrderAction.UnSalesIn && (f = _.find(i, function(t) { return t.id == n.InOrderAction.ConsignmentIn }), s.currentInventoryInOrder.inOrderAction = f ? n.InOrderAction.ConsignmentIn : i[0].id)) : s.currentInventoryInOrder.inOrderAction === n.InOrderAction.ConsignmentIn && (s.currentInventoryInOrder.inOrderAction = n.InOrderAction.PurchaseIn);
                    v();
                    y(r.grade) },
                ot = function() { if (s.currentInventoryInOrder.inWarehouseId = s.currentInventoryInOrder.warehouseId, s.currentInventoryInOrder.warehouseId == -1) { if (s.currentInventoryInOrder.inOrderAction != n.InOrderAction.ConsignmentIn && (s.uiState.consignmentDealer.visible = !0), s.baseData.dealerWarehouses && s.baseData.dealerWarehouses.length > 0)
                            if (s.currentInventoryInOrder.consignmentDealerId) { var t = _.find(s.baseData.dealerWarehouses, { dealerId: s.currentInventoryInOrder.consignmentDealerId });
                                t && (s.currentInventoryInOrder.inWarehouseId = t.warehouseId) } else s.currentInventoryInOrder.consignmentDealerId = s.baseData.dealerWarehouses[0].dealerId, s.currentInventoryInOrder.inWarehouseId = s.baseData.dealerWarehouses[0].warehouseId } else s.uiState.consignmentDealer.visible = !1, s.currentInventoryInOrder.consignmentDealerId = null;
                    s.$modalInstance.broadcast("WAREHOUSE_ID_CHANGE", { warehouseId: s.currentInventoryInOrder.inWarehouseId });
                    s.getProductBatchAndExpires() },
                st = function(n) { var i = n.item.context.innerText,
                        t = _.find(s.baseData.dealerWarehouses, { dealerName: i });
                    t && (s.currentInventoryInOrder.inWarehouseId = t.warehouseId, s.getProductBatchAndExpires()) },
                ht = function(t) { var i = this.dataItem(t.item.index());
                    s.currentInventoryInOrder.warehouseGrade === n.WarehouseGrade.Consignee.value ? i.id != n.InOrderAction.UnTakeIn && i.id != n.InOrderAction.UnSalesIn && i.id != n.InOrderAction.ConsignmentIn && (t.preventDefault(), u.warn({ message: "寄售仓库不支持当前入库类型" })) : i.id == n.InOrderAction.ConsignmentIn && (t.preventDefault(), u.warn({ message: "当前仓库不支持寄售入库" })) },
                ct = function(n, t) { if (t.expiredDate && t.batchNumber) { var i = o.open({ animation: !0, backdrop: "static", template: "<inventory-in-order-input-unicode-dialog-view><\/inventory-in-order-input-unicode-dialog-view>", controller: "InventoryInInputOrderUnicodeDialogCtrl", windowClass: "ares-medium-modal-content product-batch-wider", resolve: { host: function() { return { sku: n, batch: t } } } });
                        i.result.then(function(n) { n && (t.unicodeList = n, t.count < t.unicodeList.length && (t.count = t.unicodeList.length), s.calcTotalAmount()) }) } else { u.warn({ message: "请先录入批号、效期" }); return } },
                lt = function(t) { if (t.unicodeGenerateMode == n.ProductUnicodeGenerateMode.ByUDI) return !0; if (t.unicodeGenerateMode == n.ProductUnicodeGenerateMode.AutoGenerate) switch (parseInt(s.currentInventoryInOrder.inOrderAction)) {
                        case n.InOrderAction.UnSalesIn:
                        case n.InOrderAction.UnTakeIn:
                            return !0;
                        default:
                            return !1 } else return !1 };
            (function() { s.onSelectProduct = d;
                s.refreshUi = l;
                s.focusNextInput = g;
                s.focusToNewRow = nt;
                s.findInvalidExpireDate = tt;
                s.onSave = it;
                s.onBatchExpireSelected = w;
                s.showNewProductHint = rt;
                s.onNewProductHintShown = ut;
                s.openEditProductModal = ft;
                s.refreshPackageAllowed = y;
                s.openUDIInputDialog = ct;
                s.isShowUDI = lt;
                s.uiState = { skuSelector: { visible: !0 }, warehouse: { onChange: ot, onSelect: et }, consignmentDealer: { onSelect: st, visible: !1, disabled: !1 }, orderDate: { disabled: !1 }, inOrderAction: { disabled: !1, name: "", onChange: v, onSelect: ht }, dealer: { visible: !0, disabled: !1, onChange: p }, deliverType: { visible: !0, disabled: !1, isWechatMall: !1, onChange: a }, deliver: { visible: !0, disabled: !1 }, patient: { visible: !0, disabled: !1, onChange: b, searchString: "" }, returnOrderOffice: { visible: !1 }, nameColumn: { width: "215px" }, specColumn: { width: "170px" }, priceColumn: { title: "入库单价/总额", disabled: !1 }, countColumn: { width: "130px", unitWidth: "35px" }, batchRow: { width: "370px" }, batchExpColumn: { visible: !1, showDropDownOnly: !1 }, syncToDealer: { visible: !0 }, totalStatics: { totalCount: 0, totalAmount: "0.00" }, currentSkuNotes: "", saveOnlyBtn: { visible: !0 }, isAutoUnpackingEnabled: !1, currentPopoverAnchor: null, currentPopoverProduct: null };
                s.skuAutoCompleteOptions = { mode: "inOrder", isLinkedCare: null, isCheckInventoryLog: !0, isOnlyEnabled: !0, includeZeroCount: !1 };
                s.init().then(function() { l(!0) }) })() } } }]);
supplychainModule.controller("InventoryInOrderEditModalCtrl", ["$scope", "dataDicSvc", "$q", "warehouseSvc", "warehouseUtil", "officeOptionSvc", "officeUtil", "$timeout", "aresNotification", "productSvc", "enums", "inventorySvc", "productUnitySvc", "loginContext", "$modalInstance", "host", "$rootScope", "permissionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b) { "use strict"; var ut = function() { var o = [],
                s; return n.baseData = {}, s = function(n) { return n.splice(0, 0, { id: 0, name: "请选择" }), n }, o.push(e.isRootGroup().then(function(t) { n.canCreateSpu = t && b.isAllowed("product.productInfo") })), o.push(t.warehouseDic.loadActive().then(function(t) { var i = u.filterWarehouses(t);
                i = _.sortBy(i, function(n) { return !n.isDefault });
                n.baseData.warehouses = i })), o.push(r.getDealerWarehouseList().then(function(t) { t && t.data && (n.baseData.dealerWarehouses = angular.copy(t.data)) })), o.push(t.currentOfficeWorkProviderDic.load().then(function(t) { n.baseData.handlers = s(angular.copy(t));
                n.baseData.staffs = s(angular.copy(t)) })), o.push(t.dealerDic.loadActive().then(function(t) { t = t.filter(function(n) { return n.id !== -100 });
                n.baseData.dealers = s(t) })), o.push(t.operatoryDic.load().then(function(t) { t = _.sortBy(t, "id");
                n.baseData.operatories = s(_.map(t, function(n) { return n.name = n.description, n })) })), o.push(t.departmentDic.load().then(function(t) { n.baseData.departments = s(_.map(t, function(n) { return n.name = n.itemName, n })) })), o.push(f.getOfficeOption(f.optionKeys.DefaultInOrderAction).then(function(t) { var r, i; return n.baseData.allActionOptions = [{ id: 1, name: "采购入库" }, { id: 5, name: "退领入库" }, { id: 6, name: "销售退货" }, { id: 0, name: "零散入库" }, { id: 9, name: "寄售入库" }], r = t ? t.split("|") : [], r = _.map(r, function(n) { return parseInt(n) }), i = [], n.baseData.allActionOptions.forEach(function(n) { r.indexOf(n.id) > -1 && i.push(n) }), e.getGroupProcurementMethod().then(function(t) { t !== "group" || v.isRootGroup || (i = _.filter(i, function(n) { return n.id !== c.InOrderAction.PurchaseIn }));
                    n.baseData.inOrderActions = i }) })), o.push(t.officeSettingDic.load().then(function(t) { n.uiState.isAutoUnpackingEnabled = t.isAutoUnpackingEnabled })), o.push(f.getOfficeOption(f.optionKeys.IsProcurementPriceLockEnabled).then(function(t) { n.isProcurementPriceLockEnabled = t })), n.deliverDataSource = [], i.all(o) },
        ft = function() { var s = i.defer(),
                f, y = _.find(n.baseData.handlers, function(n) { return n.userID == v.userId }),
                b = y ? y.id : 0,
                t, r, h, d; if (p.inOrderId) l.getInOrderById(p.inOrderId).success(function(t) { var f, r, i, u;
                p.action === "copyFromCancelled" ? (t.id = 0, t.state = 0, _.each(t.items, function(n) { n.unicode = null })) : p.action === "cancelAndCopy" && (n.isCancelAndCopy = !0, t.id = 0, t.state = 0, t.orderDate = moment(t.orderDate).add(-1, "d").format("YYYY-MM-DD"), _.each(t.items, function(n) { n.amount = n.businessAmount;
                    n.price = n.businessPrice;
                    n.unicode = null }));
                f = _.groupBy(t.items, "productId");
                r = _.uniq(t.items, "productId");
                _.each(r, function(n) { var t = angular.copy(f[n.productId]),
                        i = _.groupBy(t, function(n) { return n.expiredDate + "&&&" + n.batchNumber });
                    t = _.map(i, function(n) { var u = _.map(n, "unicode"),
                            t = n[0],
                            i, r; return t.unicode = null, i = 0, r = 0, _.each(n, function(n) { i += n.count;
                            r += n.amount }), t.count = i.toFixed(2), t.amount = r.toFixed(2), t.unicodeList = _.filter(u, function(n) { return !_.isEmpty(n) }), t });
                    _.each(t, function(n) { n.unicodeList || (n.unicodeList = []) });
                    n.batches = t });
                t.items = r;
                t.orderDate = moment(t.orderDate).format("YYYY-MM-DD");
                i = _.find(n.baseData.dealers, function(n) { return n.name === t.dealer });
                i && (t.dealerId = i.id, t.dealerType = i.type);
                u = _.find(n.baseData.warehouses, function(n) { return n.id == t.warehouseId });
                t.warehouseGrade = u ? u.grade : c.WarehouseGrade.Office.value;
                t.isSyncProductDealer = !0;
                n.currentInventoryInOrder = t;
                n.currentInventoryInOrder.inWarehouseId || (n.currentInventoryInOrder.inWarehouseId = n.currentInventoryInOrder.warehouseId);
                n.refreshPackageAllowed(t.warehouseGrade);
                _.each(n.currentInventoryInOrder.items, function(n) { g(n) });
                nt();
                rt(!0);
                n.uiState.patient.searchString = n.currentInventoryInOrder.relatedName;
                s.resolve(!0) });
            else if (p.inOrder) t = p.inOrder, r = _.find(n.baseData.dealers, function(n) { return n.name === t.dealer }), t.dealerId = r ? r.id : 0, t.dealerType = r ? r.type : c.OrganizationType.NormalDealer, h = t.dealerType === c.OrganizationType.ConsignmentDealer ? _.find(n.baseData.warehouses, function(n) { return n.grade === c.WarehouseGrade.Consignee.value }) : u.getDefaultWarehouse(n.baseData.warehouses), t.warehouseId = h.id, t.inWarehouseId = h.id, t.warehouseGrade = h.grade, t.receiverId = b, t.orderDate = moment().format("YYYY-MM-DD"), t.inOrderAction == c.InOrderAction.UnSalesIn && t.hasGroupSalesOrder && (t.relatedName = t.deliver, t.deliverType = 0, t.deliver = "请选择"), t.inOrderAction == c.InOrderAction.UnSalesIn && t.deliverType == c.InOrderDeliverType.WechatMall && (n.uiState.deliverType.isWechatMall = !0), r && t.inOrderAction == c.InOrderAction.PurchaseIn && (r.type == c.OrganizationType.LinkedCare || r.type == c.OrganizationType.MallDealer) && _.each(t.items, function(n) { if (angular.isArray(n.waybillInfos) && n.waybillInfos.length > 0) { var i = n.batches[0],
                        t = {};
                    _.each(n.waybillInfos, function(i) { i.batchNumber = n.isBatchNoEnabled ? i.batchNumber || "" : "";
                        i.expiredDate = n.isExpiredDateEnabled ? i.expiredDate || "" : ""; var r = i.batchNumber + "&&&" + i.expiredDate;
                        t[r] = t[r] || 0;
                        t[r] += i.count });
                    n.batches = _.map(t, function(t, r) { return _.extend({}, i, { batchNumber: r.split("&&&")[0], expiredDate: r.split("&&&")[1], unicodeList: [], count: t === 0 ? 0 : t < n.unInStorageNum ? t : n.unInStorageNum }) }) } else _.each(n.batches, function(n) { n.count = n.deliveredNum }) }), n.uiState.patient.searchString = t.relatedName, o(function() { n.currentInventoryInOrder = t;
                _.each(n.currentInventoryInOrder.items, function(n) { n.referencedTotalAmount = n.toAmount;
                    n.price = n.unInStorageNum ? (n.referencedTotalAmount / n.unInStorageNum).toFixed(2) : "0.00";
                    g(n);
                    n.toSpecification && n.toUnit && (n.toSpecAndUnit = n.toSpecification + "(" + n.toUnit + ")");
                    _.each(n.batches, function(n) { n.unicodeList || (n.unicodeList = []) }) });
                n.refreshPackageAllowed(t.warehouseGrade) }), s.resolve(!0);
            else { f = u.getDefaultWarehouse(n.baseData.warehouses); var a = f.grade,
                    k = _.find(n.baseData.warehouses, function(n) { return n.id == w.currentWarehouseId }),
                    e = n.baseData.inOrderActions[0].id;
                (f && f.grade == c.WarehouseGrade.Consignee.value || k && k.grade == c.WarehouseGrade.Consignee.value) && (a = c.WarehouseGrade.Consignee.value, d = _.find(n.baseData.inOrderActions, function(n) { return n.id == c.InOrderAction.ConsignmentIn || n.id == c.InOrderAction.UnTakeIn || n.id == c.InOrderAction.UnSalesIn }), e = d && e != c.InOrderAction.ConsignmentIn && e != c.InOrderAction.UnTakeIn && e != c.InOrderAction.UnSalesIn ? c.InOrderAction.ConsignmentIn : null);
                o(function() { n.currentInventoryInOrder = { warehouseId: w.currentWarehouseId || f.id, inWarehouseId: w.currentWarehouseId || f.id, warehouseGrade: a, orderNumber: null, orderDate: moment().format("YYYY-MM-DD"), receiverId: b, inOrderAction: e, dealerId: 0, dealer: "", state: 0, deliverType: 0, deliver: "", relatedId: 0, relatedName: "", isSyncProductDealer: !0, items: [] };
                    n.refreshPackageAllowed(a) });
                s.resolve(!0) } return s.promise },
        et = function() { var t = i.defer(); return ut().then(function() { ft().then(function() { n.skuAutoCompleteOptions.includeZeroCount = n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnSalesIn || n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnTakeIn;
                    t.resolve(!0) }) }), t.promise },
        tt = function(t, i, r) { var f = _.find(n.currentInventoryInOrder.items, function(n) { return n.productId === t.productId }),
                u = null,
                h, c, e, l; if (i == "unicode" && r && (u = _.find(t.batches, function(n) { return n.unicode == r }), u && (t.isBatchNoEnabled = !0, t.isExpiredDateEnabled = !0, t.hasInventoryLog = !0)), f) { i ? u ? (h = _.find(f.batches, function(n) { return n.batchNumber == u.batchNumber && moment(n.expiredDate).format("YYYY-MM-DD") == moment(u.expiredDate).format("YYYY-MM-DD") }), h ? (h.unicodeList.push(u.unicode), h.count++) : (c = { count: i ? 1 : 0, amount: "0.00", batchNumber: u ? u.batchNumber : "", expiredDate: u ? u.expiredDate : "", unicode: u ? u.unicode : "", unicodeList: [] }, c.unicodeList.push(u.unicode), f.batches.push(c)), d(f)) : i === "barcode" && f.batches && f.batches.length && (f.batches[f.batches.length - 1].count += 1, d(f)) : s.error("此物品已经在入库明细列表中！"); return } e = { productId: t.productId, name: t.name, producer: t.producer, specification: t.specification, unit: t.unit, price: "0.00", isBatchNoEnabled: t.isBatchNoEnabled, isExpiredDateEnabled: t.isExpiredDateEnabled, notes: "", productUnityId: t.productUnityId, isNewProduct: !t.hasInventoryLog && n.canCreateSpu, unicodeGenerateMode: t.unicodeGenerateMode, batches: [] };
            l = { count: i ? 1 : 0, amount: "0.00", batchNumber: u ? u.batchNumber : "", expiredDate: u ? u.expiredDate : "", unicode: u ? u.unicode : "", unicodeList: [] };
            u && u.unicode && l.unicodeList.push(u.unicode);
            e.batches.push(l);
            o(function() { n.currentInventoryInOrder.items.unshift(e);
                k();
                n.refreshUi();
                it(e).then(function() { nt(e) });
                y.broadcast("SKU_SELECT_ADDED", { productId: e.productId });
                i || o(function() { n.focusNextInput(null, !0) }, 0, !1) }) },
        ot = function(t) { h.get(t).success(function(t) { t.productId = t.id; var r = _.findIndex(n.currentInventoryInOrder.items, function(n) { return n.productId === t.productId }),
                    i = { productId: t.productId, name: t.name, producer: t.producer, specification: t.specification, unit: t.unit, price: "0.00", isBatchNoEnabled: t.isBatchNoEnabled, isExpiredDateEnabled: t.isExpiredDateEnabled, notes: "", productUnityId: t.productUnityId, isNewProduct: !t.hasInventoryLog && n.canCreateSpu, unicodeGenerateMode: t.unicodeGenerateMode, batches: [{ count: 0, amount: "0.00", batchNumber: "", expiredDate: "", unicodeList: [] }] };
                o(function() { n.currentInventoryInOrder.items[r] = i;
                    n.refreshUi();
                    it(i).then(function() { nt(i) }) }) }) },
        st = function(t, i) { t.batches.push({ count: 0, batchNumber: "", expiredDate: "", notes: "", amount: "0.00", unicodeList: [] });
            n.refreshUi();
            n.focusToNewRow(i) },
        ht = function(t, i, r) { t.batches.splice(i, 1);
            t.batches.length === 0 && (n.currentInventoryInOrder.items.splice(r, 1), n.$modalInstance.broadcast("SKU_SELECT_REMOVED", { productId: t.productId }));
            k();
            n.refreshUi() },
        it = function(t) { var r = i.defer(); return n.uiState.dealer.visible && n.currentInventoryInOrder.dealerId ? h.getProductDealersByProductIds({ productIds: [t.productId], dealerId: n.currentInventoryInOrder.dealerId }).success(function(n) { var i = _.find(n, function(n) { return n.productId === t.productId });
                i && (t.price = i.price.toFixed(2), d(t), r.resolve(!0)) }) : r.resolve(!0), r.promise },
        ct = function() { var t = _.pluck(n.currentInventoryInOrder.items, "productId"); return h.getProductDealersByProductIds({ productIds: t, dealerId: n.currentInventoryInOrder.dealerId }).then(function(n) { return n.data }) },
        nt = function(t) { var r = !!t,
                i = t ? [t] : n.currentInventoryInOrder.items,
                u = _.pluck(i, "productId");
            a.getProductPackageByProductIds(u).success(function(t) { var u = _.filter(i, function(n) { return n.fromProductId && n.fromProductId !== n.productId }),
                    e = _.pluck(u, "fromProductId"),
                    f;
                h.getProductsByProductIds(e).success(function(i) { _.each(u, function(r) { var u = _.find(i, function(n) { return n.id === r.fromProductId }),
                            f = _.find(t, function(n) { return n.fromProductId === r.fromProductId });
                        u && f && (u.productId = u.id, delete u.id, _.extend(r, u, { count: parseInt(r.count) / parseInt(r.packageCount), price: (parseFloat(r.amount) / parseInt(r.count) * parseInt(r.packageCount)).toFixed(2), toProductId: f.toProductId, toPackageCount: r.packageCount, toSpecAndUnit: f.toSpecAndUnit, toSpecification: f.toSpecification, toUnit: f.toUnit }), _.each(r.batches, function(n) { n.count = parseInt(n.count) / parseInt(r.packageCount) }), r.isPackage = !0, r.isUnpackingAllowed = n.currentInventoryInOrder.isUnpackingAllowed, g(r)) }) });
                f = _.filter(i, function(n) { return !n.fromProductId || n.fromProductId === n.productId });
                _.each(f, function(i) { var u = _.find(t, function(n) { return n.fromProductId === i.productId });
                    u && (_.extend(i, { toProductId: u.toProductId, toPackageCount: u.count, toSpecAndUnit: u.toSpecAndUnit, toSpecification: u.toSpecification, toUnit: u.toUnit }), i.isPackage = r ? n.uiState.isAutoUnpackingEnabled : !1, i.isUnpackingAllowed = n.currentInventoryInOrder.isUnpackingAllowed, i.isPackage && i.isUnpackingAllowed && d(i)) }) }) },
        k = function() { var t = 0,
                i = 0;
            _.each(n.currentInventoryInOrder.items, function(n) { _.each(n.batches, function(n) { t += parseInt(n.count);
                    i += parseFloat(n.amount) }) });
            n.uiState.totalStatics.totalCount = t;
            n.uiState.totalStatics.totalAmount = i.toFixed(2) },
        lt = function(t) { var o, a, v, l, s, y, h, r, p, e; if (!moment(n.currentInventoryInOrder.orderDate, "YYYY-MM-DD", !0).isValid()) return "请输入正确的单据日期 "; if (moment(n.currentInventoryInOrder.orderDate, "YYYY-MM-DD", !0).isAfter(moment())) return "单据日期不能大于当前日期 "; if (!n.currentInventoryInOrder.warehouseId || n.currentInventoryInOrder.warehouseId === "0") return "请选择入库仓库 "; if (n.currentInventoryInOrder.referenceOrderId && n.currentInventoryInOrder.referenceOrderId > 0 && n.currentInventoryInOrder.warehouseGrade == c.WarehouseGrade.Consignee.value) return "下推入库单不能选择寄售仓库 "; if (!n.currentInventoryInOrder.receiverId || n.currentInventoryInOrder.receiverId === "0") return "请选择经办人 "; if (angular.isUndefined(n.currentInventoryInOrder.inOrderAction) || _.isNull(n.currentInventoryInOrder.inOrderAction)) return "请选择入库类型"; if (n.currentInventoryInOrder.warehouseGrade === c.WarehouseGrade.Consignee.value && n.currentInventoryInOrder.inOrderAction != c.InOrderAction.UnTakeIn && n.currentInventoryInOrder.inOrderAction != c.InOrderAction.UnSalesIn && n.currentInventoryInOrder.inOrderAction != c.InOrderAction.ConsignmentIn) return "寄售仓库不支持当前入库类型"; if (n.currentInventoryInOrder.inOrderAction == c.InOrderAction.PurchaseIn && !n.currentInventoryInOrder.referenceOrderId && (!n.currentInventoryInOrder.dealerId || n.currentInventoryInOrder.dealerId === "0")) return "请选择供应商"; if ((n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnTakeIn || n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnSalesIn) && !n.uiState.deliverType.isWechatMall && (n.currentInventoryInOrder.deliverType < 0 || n.currentInventoryInOrder.deliverType === null || !n.currentInventoryInOrder.deliver || n.currentInventoryInOrder.deliver === "请选择")) return "请选择退货单位或者退货员"; if (n.uiState.patient.visible && (!n.currentInventoryInOrder.relatedId || !n.uiState.patient.searchString)) return "请选择患者"; if (n.currentInventoryInOrder.items.length === 0) return "请添加入库物品"; for (o = 0; o < n.currentInventoryInOrder.items.length; o++) { var i = n.currentInventoryInOrder.items[o],
                    u = i.batches,
                    f = _.find(u, function(n) { return !n.count }); if (f) return "物品【" + i.name + "】数量必须大于0！"; if ((n.currentInventoryInOrder.inOrderAction == c.InOrderAction.PurchaseIn || n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnSalesIn) && n.currentInventoryInOrder.referenceOrderId > 0) { if (f = _.find(u, function(n) { return n.unInStorageNum < n.count }), f) return "物品【" + i.name + "】入库数量不能大于待入库数量！"; if (u.length > 1 && (a = _.pluck(u, "count"), v = _.reduce(a, function(n, t) { return n + t }, 0), u[0].unInStorageNum < v)) return "物品【" + i.name + "】入库总数量不能大于待入库数量！" } if (f = i.isBatchNoEnabled && !i.isExpiredDateEnabled && _.find(u, function(n) { return !n.batchNumber }), f) return "物品【" + i.name + "】需要在入库时录入货物的批号！"; if (f = i.isExpiredDateEnabled && !i.isBatchNoEnabled && _.find(u, function(n) { return !n.expiredDate }), f) return "物品【" + i.name + "】有效期未录入，或当前格式不正确，正确格式为0000-00-00！"; if (f = i.isExpiredDateEnabled && i.isBatchNoEnabled && _.find(u, function(n) { return !n.expiredDate && !n.batchNumber }), f) return "物品【" + i.name + "】需要在入库时录入货物的批号或有效期，有效期正确格式为0000-00-00！"; if (l = n.findInvalidExpireDate(), l) return "物品【" + l + "】有效期格式不正确，正确格式为0000-00-00！"; for (s = 0; s < u.length; s++)
                    if (r = u[s], r.expiredDate && (r.expiredDate = moment(r.expiredDate).format("YYYY-MM-DD")), y = _.filter(u, function(n) { return n.expiredDate && (n.expiredDate = moment(n.expiredDate).format("YYYY-MM-DD")), n.batchNumber === r.batchNumber && n.expiredDate === r.expiredDate && n.unicode === r.unicode }), y.length > 1) return e = "物品【" + i.name + "】", i.isBatchNoEnabled && r.batchNumber && (e += " 批次号【" + r.batchNumber + "】"), i.isExpiredDateEnabled && r.expiredDate && (e += " 有效期【" + r.expiredDate + "】"), e + "不能重复！"; if (i.unicodeGenerateMode == c.ProductUnicodeGenerateMode.ByUDI || i.unicodeGenerateMode == c.ProductUnicodeGenerateMode.AutoGenerate && (n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnTakeIn || n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnSalesIn))
                    for (h = 0; h < i.batches.length; h++)
                        if (r = i.batches[h], p = t ? r.unicodeList.length > 0 && r.unicodeList.length != r.count : r.unicodeList.length == 0 || r.unicodeList.length != r.count, p) return e = "物品【" + i.name + "】", i.isBatchNoEnabled && r.batchNumber && (e += " 批次号【" + r.batchNumber + "】"), i.isExpiredDateEnabled && r.expiredDate && (e += " 有效期【" + r.expiredDate + "】"), e + "UDI录入数和入库数不一致" } return null },
        d = function(t, i) { var r, u, f;
            i = i || 0;
            n.currentInventoryInOrder.referenceOrderId ? (r = 0, u = 0, _.each(t.batches, function(n, i) { i < t.batches.length - 1 ? (n.amount = (t.referencedTotalAmount / t.unInStorageNum * n.count).toFixed(2), r += parseFloat(n.amount), u += n.count) : n.amount = n.count + u === t.unInStorageNum ? (t.referencedTotalAmount - r).toFixed(2) : (t.referencedTotalAmount / t.unInStorageNum * n.count).toFixed(2) })) : i === 0 ? _.each(t.batches, function(n) { n.amount = (parseFloat(t.price) * n.count).toFixed(2) }) : (f = t.batches[i], f.amount = t.batches[0].count === 0 ? "0.00" : (parseFloat(t.batches[0].amount) / t.batches[0].count * f.count).toFixed(2));
            t.isPackage && t.isUnpackingAllowed && (_.each(t.batches, function(n) { n.toNumber = n.count * t.toPackageCount }), t.toPrice = (parseFloat(t.price) / t.toPackageCount).toFixed(2));
            k() },
        g = function(t) { if (n.currentInventoryInOrder.referenceOrderId) _.each(t.batches, function(n) { n.amount = n.count === t.unInStorageNum ? t.referencedTotalAmount.toFixed(2) : (t.referencedTotalAmount / t.unInStorageNum * n.count).toFixed(2) });
            else { var i = t.batches[0];
                _.each(t.batches, function(n, r) { r === 0 ? t.price = n.count ? (parseFloat(n.amount) / n.count).toFixed(2) : "0.00" : t.amount = (parseFloat(i.amount) / i.count * n.count).toFixed(2) }) } t.isPackage && t.isUnpackingAllowed && (_.each(t.batches, function(n) { n.toNumber = n.count * t.toPackageCount }), t.toPrice = (parseFloat(t.price) / t.toPackageCount).toFixed(2));
            k() },
        at = function() { var t = angular.copy(n.currentInventoryInOrder),
                i, r; return t.dealerId && t.dealerId !== "0" && (i = _.find(n.baseData.dealers, function(n) { return n.id == t.dealerId }), i && (t.dealer = i.name)), n.uiState.deliverType.isWechatMall && (t.deliver = "微商城", t.deliverType = c.InOrderDeliverType.WechatMall), t.relatedType == 1 && (t.deliverType = c.InOrderDeliverType.Office), t.isSyncProductDealer = n.uiState.syncToDealer.visible && t.isSyncProductDealer, r = [], _.each(t.items, function(n) { _.each(n.batches, function(t) { var i = { count: t.count, batchNumber: t.batchNumber, expiredDate: t.expiredDate, amount: t.amount, unicode: t.unicode },
                        u = function(n, t) { var i = _.extend({}, n, t);
                            delete i.batches;
                            delete i.id;
                            delete i.batchAndExpires;
                            i.isPackage = n.isPackage && n.isUnpackingAllowed;
                            i.businessPrice = i.price;
                            i.businessAmount = i.amount;
                            r.push(i) };
                    _.isEmpty(t.unicodeList) ? u(n, i) : _.each(t.unicodeList, function(t) { i.price = n.price;
                        i.amount = n.price;
                        i.count = 1;
                        i.unicode = t;
                        u(n, i) }) }) }), t.items = r, t.inWarehouseId > 0 && t.warehouseId != t.inWarehouseId && (t.warehouseId = t.inWarehouseId), t },
        vt = function(t, i) { var r = t ? "保存" : "保存并执行",
                u;
            n.currentInventoryInOrder.id && (r = "编辑");
            n.isCancelAndCopy && (r = "重新入库");
            Ares.sensors.track("InventoryOperation", { OrderNumber: i.orderNumber, OperationType: "入库", OperationSubType: Ares.sensors.getInOrderActionString(parseInt(i.inOrderAction)), OperationMode: r, PatientName: i.notes });
            u = _.any(n.currentInventoryInOrder.items, function(n) { return n.isPackage && n.isUnpackingAllowed });
            u && Ares.sensors.track("InventoryOperation", { OrderNumber: i.orderNumber, OperationType: "拆包", OperationSubType: Ares.sensors.getInOrderActionString(parseInt(i.inOrderAction)), OperationMode: r }) },
        yt = function(t) { var r = i.defer(),
                u = at(),
                f; return f = n.isCancelAndCopy ? l.cancelAndAddInOrder(u, p.inOrderId) : t ? l.saveInOrder(u) : l.saveAndApproveInOrder(u), f.success(function(n) { vt(t, n);
                r.resolve({ id: n.id, state: n.state }) }).error(function(n) { n.name === "InventoryOperationException" || n.name === "AresBusinessException" ? r.reject(n.message) : r.reject("保存失败") }), r.promise },
        rt = function(t) { if (n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnSalesIn || n.currentInventoryInOrder.inOrderAction == c.InOrderAction.UnTakeIn) { t || _.each(n.currentInventoryInOrder.items, function(n) { _.each(n.batches, function(n) { n.batchNumber = "";
                        n.expiredDate = "";
                        n.unicode = "" }) }); var i = _.pluck(n.currentInventoryInOrder.items, "productId"); if (i.length === 0) return;
                l.getRecentOutedBatchAndExpireByProductIds(i, n.currentInventoryInOrder.inWarehouseId).success(function(t) { _.each(n.currentInventoryInOrder.items, function(n) { var i = _.find(t, function(t) { return t.productId === n.productId });
                        n.batchAndExpires = { recent: i.items, all: i.allItems } }) }) } },
        pt = function() { y.on("SKU_SELECT_ADD", function(n) { if (n && n.data) { var t = n.data.sku;
                    t && tt(t) } });
            y.on("TAB_SWITCHED", function() { if (n.currentInventoryInOrder) { var t = _.pluck(n.currentInventoryInOrder.items, "productId");
                    y.broadcast("SKU_EXIST_LIST", { productIds: t }) } }) };
    (function() { n.init = et;
        n.addSkuToList = tt;
        n.addBatchToSku = st;
        n.removeBatch = ht;
        n.calcOnCountOrPriceChanged = d;
        n.calcOnAmountChanged = g;
        n.validateInOrder = lt;
        n.save = yt;
        n.getCurrentDealerPrices = ct;
        n.getProductBatchAndExpires = rt;
        n.reloadSkuToList = ot;
        n.calcTotalAmount = k;
        n.isCancelAndCopy = !1;
        pt() })() }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u) { var f = this;
            this.$q = n;
            this.$timeout = t;
            this.aresDialog = i;
            this.enums = r;
            this.aresNotification = u;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/inventory/dialogs/inventory-in-order-input-unicode-dialog/inventory-in-order-input-unicode-dialog-view.html";
            this.link = function(n, t) { var i = [],
                    r = function() { var t = f.$q.defer(); return n.batch.count > i.length && i.length > 0 ? f.aresDialog.confirm("提醒", "已录入唯一码数量和入库数量不一致，是否保存？").then(function() { t.resolve() }, function() { t.reject() }) : t.resolve(), t.promise },
                    u = function() { var t = _.isEmpty(n.batch.unicodeList) && !_.isEmpty(i),
                            r = !_.isEmpty(_.difference(n.batch.unicodeList, i)); return t || r },
                    e = function() { r().then(function() { n.save(i) }) },
                    o = function() { u() ? f.aresDialog.confirm("提醒", "已录入唯一码，是否关闭？").then(function() { n.close() }) : n.close() },
                    s = function(t) { if ((t.keyCode === f.enums.KeyCode.Enter || t.key === "Enter") && !_.isEmpty(t.target.value)) { n.unicode = t.target.value; var r = _.find(i, function(t) { return t == n.unicode });
                            r ? f.aresNotification.error("该唯一码已添加") : i.push(n.unicode);
                            n.unicode = "";
                            t.target.value = "" } },
                    h = function(n) { var t = _.findIndex(i, function(t) { return t == n });
                        i.splice(t, 1) },
                    c = function() { _.each(n.batch.unicodeList, function(n) { i.push(n) }) },
                    l = function() { i.splice(0, i.length) };
                n.clickClose = o;
                n.clickSave = e;
                n.unicode = "";
                n.codeList = i;
                n.addCode = s;
                n.removeCode = h;
                n.clearAllCode = l,
                    function() { Ares.centerModal(t.closest(".modal-dialog"));
                        c() }() } } return n.$inject = ["$q", "$timeout", "aresDialog", "enums", "aresNotification"], n }();
    supplychainModule.directive("inventoryInOrderInputUnicodeDialogView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r) { this.$q = n;
            this.$scope = t;
            this.$modalInstance = i;
            this.host = r; var u = function(n) { i.close(n) },
                f = function() { i.close(!1) };
            t.save = u;
            t.close = f;
            t.sku = r.sku;
            t.batch = r.batch } return n.$inject = ["$q", "$scope", "$modalInstance", "host"], n }();
    supplychainModule.controller("InventoryInInputOrderUnicodeDialogCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryInWarehouseOrderListView", ["$log", "$q", "$timeout", "$window", "$modal", "inventoryInOrderUtil", "supplyChainPrintUtil", "eventAggregator", "inventoryUtil", "loginContext", function(n, t, i, r, u, f, e, o, s, h) { return { restrict: "E", templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-in-warehouse-order-list/inventory-in-warehouse-order-list-view.html", link: function(n, t) { "use strict"; var i = function() { var n = t.find(".in-out-warehouse-body-tbody");
                    n.height(angular.element(r).height() - 220) },
                c = function(n) { var t = n.id;
                    f.viewOperationLog(t, "InventoryInOrder") },
                l = function(t) { var i = angular.copy(t);
                    e.printInventoryInOrder(i, n) },
                a = function(n, t) { var i = n.productId || n.id;
                    o.publish(o.events.ProductSelected, i, t.delegateTarget) },
                v = function() { s.getProductCodeOptions().then(function(t) { n.allowInsideCode = t.allowInsideCode }) },
                y = function(t) { var i = u.open({ animation: !0, backdrop: "static", template: "<inventory-in-order-count-view><\/inventory-out-order-count-view>", controller: "InventoryInOrderCountCtrl", windowClass: "ares-medium-modal-content inventory-in-order-count-model-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { orderItem: angular.copy(t), isInventoryCostVisible: n.isInventoryCostVisible } } } }) },
                p = function(t) { var i = t.referenceOrderId > 0; return t && t.inOrderAction && ((t.inOrderAction == 1 || t.inOrderAction == 6) && !i || t.inOrderAction == 1 && n.isProcurementPriceAllowed && i) },
                w = function(t) { return t && t.inOrderAction != 5 && (!t.referenceOrderId || t.referenceOrderId > 0 && t.inOrderAction == 1 && n.isProcurementPriceAllowed) },
                b = function(n) { return n && n.inOrderAction != 5 && !n.referenceOrderId };
            (function() { n.printOrder = l;
                n.viewOperationLog = c;
                n.onSelectProduct = a;
                n.showBatchItemDialog = y;
                n.isShowBizPrice = p;
                n.isShowPrice = w;
                n.isShowTotalPrice = b;
                n.isProcurementPriceAllowed = h.isProcurementPriceAllowed;
                v();
                i() })() } } }]);
supplychainModule.controller("inventoryInWarehouseOrderListCtrl", ["$log", "$scope", "$q", "$filter", "inventorySvc", "aresNotification", "permissionProvider", "dataDicSvc", "dataHost", "inventoryUtil", "enums", "$modalInstance", "inventoryInOrderUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a) { "use strict";
    t.states = [{ id: 0, name: "待处理" }, { id: 1, name: "已处理" }, { id: 2, name: "已作废" }]; var y = function() { var n = i.defer(); return o.warehouseDic.load().then(function(i) { t.warehouses = i;
                n.resolve(!0) }), n.promise },
        p = function() { var n = i.defer(); return o.userNameDic.load().then(function(i) { t.createUsers = i;
                n.resolve(!0) }), n.promise },
        w = function() { var n = i.defer(); return o.currentOfficeWorkProviderDic.load().then(function(i) { t.receivers = i;
                n.resolve(!0) }), n.promise },
        v = function() { b(s.inOrder) },
        b = function(r) { var e = i.defer(); return u.getInOrderById(r.id).success(function(n) { k(n);
                h.setBatchesByProductId(n);
                t.currentInventoryOrder = n;
                t.totalCount = 0;
                n.items && n.items.length > 0 && n.items.forEach(function(n) { t.totalCount += n.count });
                e.resolve(!0) }).error(function(t) { f.error("无法获取订单详情");
                n.log(t);
                e.reject() }), e.promise },
        k = function(n) { var o = r("toDeliverTypeStr"),
                i, u, f, e;
            n.operatorId && (i = _.find(t.createUsers, function(t) { return t.id == n.operatorId }), n.operatorName = i ? i.name : "");
            n.state != null && (u = _.find(t.states, function(t) { return t.id == n.state }), n.stateStr = u ? u.name : "");
            n.receiverId && (f = _.find(t.receivers, function(t) { return t.id == n.receiverId }), n.receiverStr = f ? f.name : "");
            n.orderDate && (e = moment(n.orderDate).format("YYYY-MM-DD"), n.orderDateStr = e);
            n.deliverTypeStr = o(n.deliverType) },
        d = function() { l.dismiss("cancel") },
        g = function() { return a.isPatientRequiredForInOrder(t.currentInventoryOrder) };
    (function() { t.init = v;
        t.close = d;
        t.isPatientRequireForOrder = g;
        y().then(function() { p().then(function() { w().then(function() { v() }) }) }) })() }]);
supplychainModule.directive("inventoryOutOrderBatchDialogView", ["$log", "$modal", "$timeout", "loginContext", function(n, t, i) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-out-order-batch-dialog/inventory-out-order-batch-dialog-view.html", link: function(n, t) { var r = function(r, u) { if (u.keyCode === 13) { var f = t.find(".table-main input");
                        f.length === r && (n.save(), r = 0);
                        f[r].focus();
                        angular.isFunction(f[r].select) && i(function() { f[r].select() }, 0, 50) } },
                u = function() { var n = t.find(".table-main input");
                    n && n[0] && (n[0].focus(), angular.isFunction(n[0].select) && i(function() { n[0].select() }, 0, 50)) };
            (function() { n.changeEnter = r;
                i(function() { Ares.centerModal(t.closest(".modal-dialog"));
                    u() }, 5) })() } } }]);
supplychainModule.controller("InventoryOutOrderBatchDialogCtrl", ["$q", "$scope", "$modalInstance", "host", "aresNotification", function(n, t, i, r, u) { "use strict"; var o = function() { i.close(!1) },
        s = function() { _.each(t.orderItem.batches, function(n) { f(n) }) },
        f = function(n) { if (t.isOnlyShow) n.outCount = n.count;
            else if (n.outCount > n.count && !t.isAllowExceedInventoryCount && (n.outCount = n.count), n.outCount === n.count) n.amount = n.batchTotalAmount;
            else { var i = Ares.priceToFixed(n.outCount * n.price);
                n.amount = t.isAllowExceedInventoryCount ? i : _.min([i, n.batchTotalAmount]) } e() },
        e = function() { var n = 0,
                i = 0;
            angular.forEach(t.orderItem.batches, function(t) { t.outCount = t.outCount * 1 || 0;
                t.amount = t.amount * 1 || 0;
                n += t.outCount;
                i += t.amount });
            t.orderItem.outCount = n;
            t.orderItem.amount = i;
            t.orderItem.price = Ares.priceToFixed(i / n) },
        h = function() { var n; return !t.isAllowExceedInventoryCount && (n = _.find(t.orderItem.batches, function(n) { return n.outCount > n.count }), n) ? "物品【" + t.orderItem.product.name + "】库存数不足！" : t.orderItem.unOutStorageNum && t.orderItem.outCount > t.orderItem.unOutStorageNum ? "出库数量大于待出库数量，请重新输入出库数量！" : "" },
        c = function() { if (!t.isOnlyShow) { e(); var n = h(); if (n) { u.error(n); return } } i.close(t.orderItem) },
        l = function(n) { if ((n.keyCode === 13 || n.key === "Enter") && t.unicodeSearchKeyword.value) { var i = _.find(t.orderItem.batches, function(n) { return n.unicode === t.unicodeSearchKeyword.value });
                i ? i.outCount === 1 ? u.info("该唯一码对应的批次已添加") : (i.outCount = 1, f(i), u.success("该唯一码批次添加成功")) : u.error("找不到该唯一码对应的批次");
                t.unicodeSearchKeyword.value = "" } };
    (function() { t.close = o;
        t.save = c;
        t.onCountChanged = f;
        t.orderItem = r.orderItem;
        t.isOnlyShow = r.isOnlyShow;
        t.isInventoryCostVisible = r.isInventoryCostVisible;
        t.isExpireDateVisible = r.orderItem.batches.some(function(n) { return n.expiredDate });
        t.isBatchNumberVisible = r.orderItem.batches.some(function(n) { return n.batchNumber });
        t.isUnicodeVisible = r.orderItem.batches.some(function(n) { return n.unicode });
        t.isAllowExceedInventoryCount = r.isAllowExceedInventoryCount;
        t.onUnicodeSearch = l;
        t.unicodeSearchKeyword = { value: "" };
        s() })() }]);
supplychainModule.directive("inventoryOutOrderEditModalView", ["$log", "$q", "$window", "$rootScope", "eventAggregator", "$timeout", "$modal", "practiceSvc", "dataDicSvc", "enums", "warehouseUtil", "loginContext", "numberUtil", "aresDialog", "inventoryUtil", "aresTreeViewUtil", "moduleOptionProvider", "aresConfirmDialog", "permissionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k) { "use strict"; return { templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-out-order-edit-modal/inventory-out-order-edit-modal-view.html", replace: !0, link: function(n, t) { var w = function(n, t) { var i = n.productId;
                    u.publish(u.events.ProductSelected, i, t.delegateTarget);
                    Ares.retainOnePopover() },
                d = function(i, r) { var u = e.open({ animation: !0, backdrop: "static", template: "<inventory-out-order-batch-dialog-view><\/inventory-out-order-batch-dialog-view>", controller: "InventoryOutOrderBatchDialogCtrl", windowClass: "ares-medium-modal-content product-batch-wider inventory-out-order-batch-dialog-wrapper", resolve: { host: function() { return { orderItem: angular.copy(i), isOnlyShow: 0, isInventoryCostVisible: n.uiState.cost.visible, isAllowExceedInventoryCount: n.isCancelAndCreate } } } });
                    u.result.then(function(u) { if (u && (i.batches = u.batches, i.outCount = u.outCount, i.businessPrice && n.currentInventoryOutOrder.dealer && (i.businessAmount = Ares.priceToFixed(i.outCount * i.businessPrice)), n.refreshTotalAmount()), n.uiState.priceColumn.title) s(null, !0);
                        else if (!r && !n.currentInventoryOutOrder.id && !n.isFromCopyCancel && !n.isCancelAndCreate) { var e = t.find(".sku-auto-complete-selector-view").find("input");
                            e.length > 0 && f(function() { e.focus() }, 100, !1) } }) },
                s = function(n, i) { f(function() { var u, e, o; if (i) u = r.find("tr:first").find("input:first").focus(), angular.isFunction(u[0].select) && f(function() { u[0].select() }, 0, 50);
                        else { if (!n || n.keyCode !== 13) return; if (e = angular.element(n.target), u = e.closest("td").find("input:last"), u.length > 0 && e[0] !== u[0]) { u.focus();
                                angular.isFunction(u[0].select) && f(function() { u[0].select() }, 0, 50); return } if (u = e.closest("td").nextAll(":not(.disabled):not(.actions-td):first").find("input:first"), u.length > 0) { u.focus();
                                angular.isFunction(u[0].select) && f(function() { u[0].select() }, 0, 50); return } o = t.find(".sku-auto-complete-selector-view").find("input");
                            o.length > 0 && o.focus() } }, 0, !1) },
                g = function(t) { var i = t.count && t.unOutStorageNum > 0 > t.unOutStorageNum ? t.unOutStorageNum : t.count,
                        r = parseInt(t.outCount);
                    t.outCount = r > i && !n.isCancelAndCreate ? i : r;
                    t.businessPrice > 0 && (t.businessAmount = Ares.priceToFixed(t.outCount * t.businessPrice));
                    t.businessAmount = (t.outCount * parseFloat(t.businessPrice)).toFixed(2);
                    n.refreshTotalAmount() },
                nt = function(t) { t.businessAmount = angular.isNumber(t.outCount) ? (t.outCount * parseFloat(t.businessPrice)).toFixed(2) : "0.00";
                    n.refreshTotalAmount() },
                tt = function(t) { t.businessPrice = parseInt(t.outCount) > 0 ? (parseFloat(t.businessAmount) / parseInt(t.outCount)).toFixed(2) : "0.00";
                    n.refreshTotalAmount() },
                c = function(t) { t && (n.currentInventoryOutOrder.relatedId = t.id, n.currentInventoryOutOrder.relatedName = t.name, n.uiState.patient.searchString = t.name) },
                it = function() { var t = [],
                        i;
                    n.currentInventoryOutOrder && n.currentInventoryOutOrder.items && (t = _.pluck(n.currentInventoryOutOrder.items, "productId"));
                    i = _.find(n.dealers, { name: n.currentInventoryOutOrder.dealer });
                    i && t.length > 0 && n.getProductDealersByProductIds(t, i.id).then(function() { if (n.productDealers.length > 0) { var t = 0;
                            angular.forEach(n.currentInventoryOutOrder.items, function(i) { var r = _.find(n.productDealers, function(n) { return n.productId === i.productId && n.price > 0 });
                                r && t++ });
                            t > 0 && b.warn({ message: "检测到有" + t + "个物品在该供应商下有报价，需要更新这些物品的报价吗？", onConfirm: function() { angular.forEach(n.currentInventoryOutOrder.items, function(t) { var i = _.find(n.productDealers, function(n) { return n.productId === t.productId });
                                        i && (t.businessPrice = i.price, t.outCount > 0 && (t.businessAmount = Ares.priceToFixed(t.outCount * t.businessPrice))) });
                                    n.refreshTotalAmount() }, onCancel: function() {} }) } }) },
                a = function() { n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.TakeOut ? (n.uiState.consigneeType.visible = !0, n.uiState.consigneeType.disabled = !1, n.uiState.consigneeType.label = "收货单位", n.uiState.dealer.visible = !1, n.uiState.patient.visible = !1, n.uiState.express.visible = !1, n.uiState.priceColumn.title = !1, parseInt(n.currentInventoryOutOrder.consigneeType) > 2 && (n.currentInventoryOutOrder.consigneeType = "-1"), o()) : n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.ProcurementReturnOut ? (n.uiState.consigneeType.visible = !1, n.uiState.dealer.visible = !0, n.uiState.patient.visible = !1, n.uiState.express.visible = !1, n.uiState.priceColumn.title = "退货价/总额", t.find("#inventory-out-order-edit-modal-dealer-dropdown").data("kendoDropDownList").value(n.currentInventoryOutOrder.dealer || "请选择")) : n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.SalesOut ? (n.uiState.consigneeType.visible = !0, n.uiState.consigneeType.disabled = !0, n.uiState.consigneeType.label = "销售员", n.uiState.dealer.visible = !1, n.uiState.patient.visible = !0, n.uiState.express.visible = !1, n.uiState.priceColumn.title = "销售价/总额", n.currentInventoryOutOrder.consigneeType = h.InOrderDeliverType.Provider, n.getSkuListSalesPrices(), o()) : (n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.NormalOut || n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.BrokenOut) && (n.uiState.consigneeType.visible = !1, n.uiState.dealer.visible = !1, n.uiState.patient.visible = !1, n.uiState.express.visible = !1, n.uiState.priceColumn.title = !1) },
                v = function() { if (n.currentInventoryOutOrder.outWarehouseId = n.currentInventoryOutOrder.warehouseId, n.currentInventoryOutOrder.warehouseId == -1)
                        if (n.uiState.consignmentDealer.visible = !0, n.baseData.dealerWarehouses && n.baseData.dealerWarehouses.length > 0)
                            if (n.currentInventoryOutOrder.consignmentDealerId) { var t = _.find(n.baseData.dealerWarehouses, { dealerId: n.currentInventoryOutOrder.consignmentDealerId });
                                t && (n.currentInventoryOutOrder.outWarehouseId = t.warehouseId) } else n.currentInventoryOutOrder.consignmentDealerId = n.baseData.dealerWarehouses[0].dealerId, n.currentInventoryOutOrder.outWarehouseId = n.baseData.dealerWarehouses[0].warehouseId;
                    else b.warn({ message: "当前诊所寄售仓库暂无寄售供应商" });
                    else n.uiState.consignmentDealer.visible = !1, n.currentInventoryOutOrder.consignmentDealerId = null;
                    n.$modalInstance.broadcast("WAREHOUSE_ID_CHANGE", { warehouseId: n.currentInventoryOutOrder.outWarehouseId }) },
                rt = function(t) { var r = t.item.context.innerText,
                        i = _.find(n.baseData.warehouses, { name: r });
                    n.currentInventoryOutOrder && n.currentInventoryOutOrder.items && n.currentInventoryOutOrder.items.length > 0 ? (t.preventDefault(), b.confirm({ message: "切换出库仓库将清空出库物品列表" }).then(function() { n.currentInventoryOutOrder.items = [];
                        n.currentInventoryOutOrder.warehouseId = i.id;
                        n.currentInventoryOutOrder.outWarehouseId = i.id;
                        y(i);
                        v();
                        n.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: [] }) })) : y(i) },
                ut = function(t) { var r = t.item.context.innerText,
                        i = _.find(n.baseData.dealerWarehouses, { dealerName: r });
                    i && (n.currentInventoryOutOrder && n.currentInventoryOutOrder.items && n.currentInventoryOutOrder.items.length > 0 ? (t.preventDefault(), b.confirm({ message: "切换寄售供应商将清空出库物品列表" }).then(function() { n.currentInventoryOutOrder.outWarehouseId = i.warehouseId;
                        n.currentInventoryOutOrder.items = [];
                        n.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: [] }) })) : n.currentInventoryOutOrder.outWarehouseId = i.warehouseId, n.$modalInstance.broadcast("WAREHOUSE_ID_CHANGE", { warehouseId: n.currentInventoryOutOrder.outWarehouseId })) },
                ft = function(t) { var i = this.dataItem(t.item.index());
                    n.currentInventoryOutOrder.warehouseGrade === h.WarehouseGrade.Consignee.value && i.id != h.OutOrderAction.TakeOut && i.id != h.OutOrderAction.SalesOut && (t.preventDefault(), b.warn({ message: "寄售仓库不支持当前出库类型" })) },
                y = function(t) { if (n.currentInventoryOutOrder.warehouseGrade = t.grade, t.grade === h.WarehouseGrade.Consignee.value) { var i = _.find(n.baseData.outOrderActions, function(n) { return n.id == h.OutOrderAction.TakeOut || n.id == h.OutOrderAction.SalesOut });
                        n.currentInventoryOutOrder.outOrderAction = i ? i.id : null;
                        a() } },
                o = function() { var t = n.currentInventoryOutOrder.consignee;
                    n.currentInventoryOutOrder.consigneeType === "-1" && (n.consigneeDataSource = [{ id: 0, name: "请选择" }]);
                    n.currentInventoryOutOrder.consigneeType == h.InOrderDeliverType.Provider ? n.consigneeDataSource = n.baseData.staffs : n.currentInventoryOutOrder.consigneeType == h.InOrderDeliverType.Operatory ? n.consigneeDataSource = n.baseData.operatories : n.currentInventoryOutOrder.consigneeType == h.InOrderDeliverType.Department && (n.consigneeDataSource = n.baseData.departments);
                    f(function() { if (n.consigneeDataSource && n.consigneeDataSource.length !== 0) { var i = _.any(n.consigneeDataSource, function(n) { return n.name === t });
                            n.currentInventoryOutOrder.consignee = i ? t : "请选择" } else n.currentInventoryOutOrder.consignee = n.currentInventoryOutOrder.consignee || "请选择" }) },
                et = function(t) { f(function() { t && (n.uiState.outOrderAction.onChange(), n.uiState.consigneeType.onChange());
                        n.currentInventoryOutOrder.referenceOrderId && (n.uiState.outOrderAction.disabled = !0, n.uiState.warehouse.disabled = !0, n.uiState.outOrderAction.name = _.find(n.allActionOptions, function(t) { return t.id == n.currentInventoryOutOrder.outOrderAction }).name, n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.TakeOut && (n.uiState.consigneeType.disabled = !0, n.uiState.consignee.disabled = !0), n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.SalesOut && (n.uiState.patient.disabled = !0, n.uiState.priceColumn.title = !1, n.uiState.consigneeType.isWechatMall && n.currentInventoryOutOrder.expressInfo && (n.uiState.express.visible = !0), n.currentInventoryOutOrder.relatedType === h.SalesOrderType.Patient ? (n.uiState.patient.title = "患者", n.uiState.consigneeType.disabled = !0, n.uiState.consignee.disabled = !0) : n.currentInventoryOutOrder.relatedType === h.SalesOrderType.Office && (n.uiState.patient.title = "收货机构", n.uiState.consigneeType.disabled = !0, n.uiState.consignee.disabled = !1, n.currentInventoryOutOrder.consignee = "请选择")), n.currentInventoryOutOrder.outOrderAction == h.OutOrderAction.ProcurementReturnOut && (n.uiState.dealer.disabled = !0, n.uiState.priceColumn.title = !1));
                        p() }) },
                r = t.find(".table-main-content"),
                p = function() { f(function() { var n = angular.element(i).height() - 210;
                        n -= angular.element(".basic-info-form").height();
                        r.height(n);
                        r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } });
                        t.find("[data-toggle=tooltip]").tooltip() }, 0, !1) };
            (function() { n.uiState = { outOrderAction: { disabled: !1, onChange: a, onSelect: ft }, warehouse: { onChange: v, onSelect: rt, disabled: !1 }, dealer: { visible: !1, disabled: !1 }, consignmentDealer: { onSelect: ut, visible: !1, disabled: !1 }, consigneeType: { label: "收货单位", disabled: !1, visible: !1, isWechatMall: !1, onChange: o }, consignee: { disabled: !1 }, patient: { title: "患者", visible: !1, searchString: "", onChange: c }, express: { visible: !1 }, priceColumn: { title: "销售价/总额", disabled: !1 }, cost: { visible: l.isInventoryCostAllowed }, skuSelector: { visible: !0 }, currentSkuNotes: "" };
                n.skuAutoCompleteOptions = { mode: "outOrder", isLinkedCare: null };
                n.allowSalingOutStock = k.isAllowed("featureRelation.salingOutStock");
                n.showBatchItemDialog = d;
                n.onSelectedProduct = w;
                n.onCountChanged = g;
                n.onPriceChanged = nt;
                n.onAmountChanged = tt;
                n.onPatientSelected = c;
                n.onChangeInventoryOutDealer = it;
                n.initScrollbar = p;
                n.focusNextInput = s;
                n.init().then(function() { et(!0) }) })() } } }]);
supplychainModule.controller("InventoryOutOrderEditModalCtrl", ["$log", "$scope", "$rootScope", "$timeout", "$modalInstance", "$q", "$modal", "$document", "officeOptionSvc", "aresNotification", "enums", "inventoryProductSvc", "productSvc", "inventorySvc", "host", "eventAggregator", "inventoryInOrderUtil", "warehouseUtil", "loginContext", "inventoryUtil", "officeUtil", "inventoryOutOrderUtil", "dataDicSvc", "practiceSvc", "aresConfirmDialog", "warehouseSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt, ut) { "use strict"; var ot = function(n, i, f) { var l = function(n) { r(function() { if (t.currentInventoryOutOrder.items.splice(0, 0, n), u.broadcast("SKU_SELECT_ADDED", { productId: n.productId }), i === "unicode") { var e = _.find(n.batches, function(n) { return n.unicode === f });
                            e && (e.outCount = 1, e.amount = e.price * 1, n.outCount = _.reduce(n.batches, function(n, t) { return n + (t.outCount || 0) }, 0), t.refreshTotalAmount(), h.success("该唯一码批次添加成功")) } else t.currentInventoryOutOrder.items[0].isSingleBatch ? t.refreshTotalAmount() : t.showBatchItemDialog(t.currentInventoryOutOrder.items[0]);
                        t.initScrollbar();
                        i || r(function() { t.focusNextInput(null, !0) }, 0, !1) }) },
                e = angular.copy(n),
                o, s, a, v; if (e != null) { if (o = _.find(t.currentInventoryOutOrder.items, function(n) { return n.productId == e.productId }), o) { i === "barcode" ? o.isSingleBatch ? o.outCount < o.count ? o.outCount++ : h.error("此物品数量已与当前仓库的库存数量相同") : t.showBatchItemDialog(o) : i === "unicode" ? (s = _.find(o.batches, function(n) { return n.unicode === f }), s && (s.outCount === 1 ? h.info("该唯一码对应的批次已添加") : (s.outCount = 1, s.amount = s.price * 1, o.outCount = _.reduce(o.batches, function(n, t) { return n + (t.outCount || 0) }, 0), t.refreshTotalAmount(), h.success("该唯一码批次添加成功")))) : h.error("此物品已经在出库物品列表中！"); return } t.currentInventoryOutOrder.items = t.currentInventoryOutOrder.items || [];
                a = 0;
                angular.forEach(e.batches, function(n) { n.id = 0;
                    n.batchTotalAmount = n.amount;
                    n.amount = 0;
                    a += n.count });
                e.isSingleBatch = e.batches.length === 1 && !e.batches[0].batchNumber && !e.batches[0].expiredDate;
                e.isSingleBatch && (e.price = e.batches[0].price);
                e.outCount = e.isSingleBatch ? 1 : "";
                e.count = a;
                e.amount = 0;
                t.currentInventoryOutOrder.dealer && t.currentInventoryOutOrder.dealer !== "请选择" ? (v = _.find(t.baseData.dealers, { name: t.currentInventoryOutOrder.dealer }), t.getProductDealersByProductIds([e.productId], v.id).then(function() { if (t.productDealers.length > 0) { var n = _.find(t.productDealers, function(n) { return n.productId === e.productId && n.price > 0 });
                        n ? (e.businessPrice = n.price.toFixed(2), e.businessAmount = angular.isNumber(e.outCount) ? (e.outCount * parseFloat(e.businessPrice)).toFixed(2) : "0.00") : (e.businessPrice = "0.00", e.businessAmount = "0.00") } l(e) })) : t.currentInventoryOutOrder.outOrderAction == c.OutOrderAction.SalesOut ? lt([e.productId]).then(function(n) { n && n[0] ? (e.businessPrice = n[0].salesPrice.toFixed(2), e.businessAmount = angular.isNumber(e.outCount) ? (e.outCount * parseFloat(e.businessPrice)).toFixed(2) : "0.00") : (e.businessPrice = "0.00", e.businessAmount = "0.00");
                    l(e) }) : t.currentInventoryOutOrder.outOrderAction == c.OutOrderAction.ProcurementReturnOut ? (e.businessPrice = "0.00", e.businessAmount = "0.00", l(e)) : l(e) } },
        vt = function(n, i) { t.currentInventoryOutOrder && t.currentInventoryOutOrder.items && (n < 0 || n > t.currentInventoryOutOrder.items.length || (t.currentInventoryOutOrder.items.splice(n, 1), ft(), u.broadcast("SKU_SELECT_REMOVED", { productId: i.productId }))) },
        st = function() { var n, i; if (t.currentInventoryOutOrder.warehouseId == 0) return "请选择出库仓库 ！"; if (t.currentInventoryOutOrder.warehouseId == -1 && !t.currentInventoryOutOrder.outWarehouseId) return "请选择寄售供应商 ！"; if (t.currentInventoryOutOrder.warehouseGrade == c.WarehouseGrade.Consignee.value && t.currentInventoryOutOrder.outOrderAction != c.OutOrderAction.TakeOut && t.currentInventoryOutOrder.outOrderAction != c.OutOrderAction.SalesOut) return "寄售仓库仅支持领用和销售出库 ！"; if (!d.checkOrderDateValid(t.currentInventoryOutOrder.orderDate)) return "请输入单据日期 ！"; if (d.checkOrderGreaterThanToday(t.currentInventoryOutOrder.orderDate)) return "单据日期不能大于当前日期 ！"; if (!t.currentInventoryOutOrder.senderId || t.currentInventoryOutOrder.senderId === "0") return "请选择经办人 ！"; if (t.currentInventoryOutOrder.outOrderAction == c.OutOrderAction.TakeOut && (t.currentInventoryOutOrder.consigneeType === "-1" || !t.currentInventoryOutOrder.consignee || t.currentInventoryOutOrder.consignee === "请选择")) return "请选择收货单位和收货人 ！"; if (t.currentInventoryOutOrder.outOrderAction == c.OutOrderAction.ProcurementReturnOut && (!t.currentInventoryOutOrder.dealer || t.currentInventoryOutOrder.dealer === "请选择")) return "请选择供应商！"; if (t.currentInventoryOutOrder.outOrderAction == c.OutOrderAction.SalesOut)
                if (t.uiState.consigneeType.isWechatMall) { if (!t.currentInventoryOutOrder.expressCompany) return "请选择快递公司！"; if (!t.currentInventoryOutOrder.expressOrderNo) return "请填写快递单号！" } else { if (t.currentInventoryOutOrder.consigneeType === "-1" || !t.currentInventoryOutOrder.consignee || t.currentInventoryOutOrder.consignee === "请选择") return "请选择销售员 ！"; if (t.uiState.patient.visible && t.allowSalingOutStock && (!t.currentInventoryOutOrder.relatedId || !t.currentInventoryOutOrder.relatedName)) return "请选择患者 ！" } if (t.currentInventoryOutOrder.items && t.currentInventoryOutOrder.items.length > 0) { if (!t.isCancelAndCreate && (n = _.find(t.currentInventoryOutOrder.items, function(n) { return n.outCount > n.count }), n)) return i = n.name, "物品【" + i + "】库存数不足！" } else return "请添加出库物品!"; return "" },
        yt = function() { var n = angular.copy(t.currentInventoryOutOrder); return n.outWarehouseId > 0 && n.warehouseId != n.outWarehouseId && (n.warehouseId = n.outWarehouseId), n.consigneeType = n.relatedType == 1 ? 4 : n.consigneeType, n.dealer = n.outOrderAction != c.OutOrderAction.ProcurementReturnOut ? null : n.dealer === "请选择" ? null : n.dealer, n.items = pt(), t.isCancelAndCreate && (n.id = 0, n.state = 0), n },
        pt = function() { var n = []; return _.each(t.currentInventoryOutOrder.items, function(t) { var i = 0,
                    r = 0;
                _.each(t.batches, function(u, f) { var e = t.batches.length > 1 ? u.outCount : t.outCount,
                        o, s;
                    e > 0 && (o = e * t.businessPrice, (f === t.batches.length - 1 || r + e === t.outCount) && (o = t.businessAmount - i), s = _.extend({}, t, { batchNumber: u.batchNumber, expiredDate: u.expiredDate, unicode: u.unicode, count: e, amount: u.amount, businessAmount: o }), delete s.batches, delete s.id, n.push(s), r += e, i += o) }) }), n },
        ht = function(n) { var i = f.defer(),
                u = st(),
                r, e; return u ? (rt.warn({ message: u }), i.reject()) : (ft(), t.currentInventoryOutOrder.orderDate || (t.currentInventoryOutOrder.orderDate = moment(Ares.today()).format("YYYY-MM-DD")), r = yt(), n ? (e = t.isCancelAndCreate ? v.cancelAndAddOutOrder : v.saveAndApproveOutOrder, e(r, y.sourceOrderId).success(function(n) { t.currentInventoryOutOrder.id = n.id;
                i.resolve(!0) }).error(function(n) { d.showInventoryErrorMessage(n, "保存失败");
                i.reject() })) : v.saveOutOrder(r).success(function(n) { r.id !== -1 && r.id || (t.currentInventoryOutOrder.id = n.id);
                i.resolve(!0) }).error(function(n) { d.showInventoryErrorMessage(n, "保存失败");
                i.reject() })), i.promise },
        ft = function() { var n = 0,
                i = 0,
                r = 0;
            angular.forEach(t.currentInventoryOutOrder.items, function(u) { var f = angular.isNumber(u.outCount) ? u.outCount : 0,
                    e, o;
                u.batches.length > 1 ? (e = 0, angular.forEach(u.batches, function(n) { var t = parseInt(n.outCount);
                    t > 0 && (e += n.amount) }), u.amount = e, u.price = f ? Ares.priceToFixed(e / f) : 0) : (o = Ares.priceToFixed(u.price * f), u.price = f === 0 ? 0 : Ares.priceToFixed(u.batches[0].price), f === u.count ? u.amount = u.batches[0].batchTotalAmount : (o = Ares.priceToFixed(u.price * f), u.amount = t.isCancelAndCreate ? o : _.min([o, u.batches[0].batchTotalAmount])));
                n += u.amount;
                i += f;
                r += parseFloat(u.businessAmount) });
            t.currentInventoryOutOrder.amount = Ares.priceToFixed(n);
            t.currentInventoryOutOrder.count = i;
            t.currentInventoryOutOrder.businessAmount = Ares.priceToFixed(r) },
        wt = function() { Ares.ensureNotDuplicated("InventoryOutOrderSaveCheck") && ht().then(function() { t.currentInventoryOutOrder.state === 0 && p.publish(p.events.RefreshIventoryHint, null, "InventoryOutOrderEditCtrl");
                h.success("保存成功"); var n = { id: t.currentInventoryOutOrder.id, state: 0 };
                u.close(n) }) },
        bt = function() { var n, i;
            Ares.ensureNotDuplicated("InventoryOutOrderApproveCheck") && (n = st(), n ? rt.warn({ message: n }) : (n = "您确定执行该单据吗？单据执行后库存将发生变更", i = _.find(t.currentInventoryOutOrder.items, function(n) { return !n.isSingleBatch && !n.outCount }), i && (n = "当前有多批次的物品【" + i.name + "】出库数量为0，<br>未选择批次，确定执行出库操作吗？"), rt.warn({ message: n, onConfirm: function() { ht(!0).then(function() { p.publish(p.events.RefreshIventoryHint, null, "InventoryOutOrderEditCtrl"); var n = { id: t.currentInventoryOutOrder.id, state: 1 };
                        u.close(n);
                        h.success("出库成功!");
                        Ares.sensors.track("InventoryOutOrderEditCtrl", { PatientName: t.currentInventoryOutOrder.notes, OperationType: "直接出库" }) }) }, onCancel: function() {} }))) },
        kt = function() { var n = f.defer(); return ti().then(function() { r(function() { dt().then(function() { n.resolve() }) }) }), n.promise },
        dt = function() { var i = f.defer(),
                o = moment(Ares.today()).format("YYYY-MM-DD"),
                r, n, u, e; return y.outOrder && !y.outOrder.referenceOrderId ? (et(y.outOrder), i.resolve(!0)) : y.outOrder && y.outOrder.referenceOrderId ? (r = _.pluck(y.outOrder.items, "productId"), r = _.uniq(r), l.searchInventoryProductBatch({ warehouseId: y.outOrder.outWarehouseId, productIds: r }).success(function(n) { var u = _.groupBy(y.outOrder.items, "productId"),
                    r = [];
                _.each(n, function(n) { if (n.count) { n.batchTotalAmount = n.amount;
                        n.batchTotalCount = n.count; var t = angular.copy(u[n.productId][0]);
                        _.extend(t, n);
                        r.push(t) } });
                y.outOrder.outOrderAction == c.OutOrderAction.SalesOut && y.outOrder.consigneeType == c.InOrderDeliverType.WechatMall && (t.uiState.consigneeType.isWechatMall = !0);
                y.outOrder.items = r;
                et(y.outOrder);
                i.resolve(!0) })) : y.sourceOrderId > 0 ? (y.isCancelAndCreate ? t.isCancelAndCreate = !0 : t.isFromCopyCancel = !0, gt(y.sourceOrderId, !0).then(function() { t.currentInventoryOutOrder.id = 0;
                t.currentInventoryOutOrder.state = 0;
                i.resolve(!0) })) : (n = ct(), u = parseInt(t.baseData.outOrderActions[0].id), n && n.grade == c.WarehouseGrade.Consignee.value && (e = _.find(t.baseData.outOrderActions, function(n) { return n.id == c.OutOrderAction.TakeOut || n.id == c.OutOrderAction.SalesOut }), u = e ? e.id : null), t.currentInventoryOutOrder = { count: 0, state: 0, amount: 0, consigneeType: "-1", consignee: "请选择", dealer: "请选择", orderDate: o, warehouseId: n.id, outWarehouseId: n.id, warehouseGrade: n.grade, id: 0, outOrderAction: u, senderId: k.providerId > 0 ? k.providerId : 0, relatedType: 0, expressCompany: "" }, t.currentInventoryOutOrder.warehouseGrade == c.WarehouseGrade.Consignee.value && (t.uiState.warehouse.onChange(), t.uiState.outOrderAction.onChange()), i.resolve(!0)), i.promise },
        gt = function(n, t) { var i = f.defer(); return v.getOutOrder(n, t).success(function(n) { n && (et(n, null), i.resolve(!0)) }).error(function() { h.error("无法获取出库单详情");
                i.reject() }), i.promise },
        et = function(n) { var i = { id: n.id, referenceOrderId: n.referenceOrderId, warehouseId: n.warehouseId, orderNumber: n.orderNumber, orderDate: n.referenceOrderId ? moment().format("YYYY-MM-DD") : moment(n.orderDate).format("YYYY-MM-DD"), notes: n.notes, state: n.state, consigneeType: n.consigneeType == 0 && !n.consignee ? "-1" : n.consigneeType, consignee: n.consignee, dealer: n.dealer, consignmentDealerId: n.consignmentDealerId, outWarehouseId: n.outWarehouseId, senderId: n.senderId > 0 ? n.senderId : k.providerId > 0 ? k.providerId : 0, outOrderAction: n.outOrderAction, relatedType: n.relatedType, relatedId: n.relatedId, relatedName: n.relatedName, items: [], expressInfo: n.expressInfo, expressCompany: "" },
                r, u;
            i.outOrderAction == c.OutOrderAction.SalesOut && (t.uiState.patient.searchString = i.relatedName);
            r = _.find(t.baseData.warehouses, function(t) { return t.id == n.warehouseId });
            i.warehouseGrade = r ? r.grade : c.WarehouseGrade.Office.value;
            u = _.groupBy(angular.copy(n.items), "productId");
            _.each(u, function(r, u) { var f = [],
                    h = 0,
                    l = 0,
                    o = 0,
                    c = 0,
                    s, e;
                angular.forEach(r, function(t) { t.outCount = n.referenceOrderId ? 0 : t.count;
                    t.count = n.referenceOrderId ? t.count : t.batchTotalCount;
                    h += t.count;
                    l += n.referenceOrderId ? t.amount : t.batchTotalAmount;
                    t.outCount > 0 && (o += t.outCount, c += t.businessAmount);
                    f.push(t) });
                f = _(f).chain().sortBy(function(n) { return n.batchNumber }).sortBy(function(n) { return n.expiredDate }).value();
                s = Ares.priceToFixed(l / h);
                s === 0 && (s = r[0].price);
                o > 0 && !t.isCancelAndCreate && (s = Ares.priceToFixed(r[0].inventoryAmount / o));
                e = { productId: u, id: u, name: r[0].name, producer: r[0].producer, specification: r[0].specification, valuationType: r[0].valuationType, unit: r[0].unit, isSingleBatch: f.length === 1 && !f[0].batchNumber && !f[0].expiredDate, batches: f, unOutStorageNum: n.referenceOrderId ? r[0].unOutStorageNum : 0, count: h, amount: r[0].inventoryAmount, price: s, businessAmount: c.toFixed(2), businessPrice: Ares.priceToFixed(c / o).toFixed(2), notes: r[0].notes };
                e.outCount = n.referenceOrderId ? e.isSingleBatch ? Math.min(r[0].unOutStorageNum, e.count) : 0 : o;
                (!i.referenceOrderId || e.unOutStorageNum > 0) && i.items.push(e) });
            i.items.length > 0 && (i.items = _.sortBy(i.items, function(n) { return -n.unOutStorageNum }));
            t.currentInventoryOutOrder = i;
            t.currentInventoryOutOrder.warehouseGrade == c.WarehouseGrade.Consignee.value && t.uiState.warehouse.onChange();
            ft() },
        ct = function() { var n = null,
                r; return t.baseData.warehouses && t.baseData.warehouses.length > 0 && (n = t.baseData.warehouses[0].id || null, r = b.getDefaultWarehouse(t.baseData.warehouses), n = r ? r.id : n), n = i.currentWarehouseId != 0 ? i.currentWarehouseId : n, n = y.warehouseId ? y.warehouseId : n, (t.currentInventoryOutOrder.id || t.currentInventoryOutOrder.referenceOrderId) && (n = t.currentInventoryOutOrder && t.currentInventoryOutOrder.warehouseId ? t.currentInventoryOutOrder.warehouseId : n), _.find(t.baseData.warehouses, function(t) { return t.id == n }) },
        ni = function(n, i) { var r = f.defer(),
                u = { productIds: n, dealerId: i }; return i && n && n.length > 0 ? a.getProductDealersByProductIds(u).success(function(n) { i && (n = _.filter(n, function(n) { return n.dealerId === i }));
                t.productDealers = n;
                r.resolve(!0) }) : (t.productDealers = [], r.resolve(!0)), r.promise },
        lt = function(n) { var t = f.defer(); return a.getProductSalesPriceByProductIds(n).success(function(n) { t.resolve(n) }), t.promise },
        ti = function() { var n = [],
                i; return t.baseData = {}, i = function(n) { return n.splice(0, 0, { id: 0, name: "请选择" }), n }, n.push(tt.warehouseDic.loadActive().then(function(n) { var i = b.filterWarehouses(n);
                i = _.sortBy(i, function(n) { return !n.isDefault });
                t.baseData.warehouses = i })), n.push(tt.currentOfficeWorkProviderDic.load().then(function(n) { t.baseData.handlers = i(angular.copy(n));
                t.baseData.staffs = i(angular.copy(n)) })), n.push(tt.dealerDic.loadActive().then(function(n) { n = n.filter(function(n) { return n.id !== -100 });
                t.baseData.dealers = i(n) })), n.push(ut.getDealerWarehouseList().then(function(n) { n && n.data && (t.baseData.dealerWarehouses = angular.copy(n.data)) })), n.push(tt.operatoryDic.load().then(function(n) { n = _.sortBy(n, "id");
                t.baseData.operatories = i(_.map(n, function(n) { return n.name = n.description, n })) })), n.push(tt.departmentDic.load().then(function(n) { t.baseData.departments = i(_.map(n, function(n) { return n.name = n.itemName, n })) })), n.push(s.getOfficeOption(s.optionKeys.DefaultOutOrderAction).then(function(n) { t.allActionOptions = [{ id: "1", name: "领用出库" }, { id: "6", name: "采购退货" }, { id: "5", name: "销售出库" }, { id: "7", name: "报废出库" }, { id: "0", name: "零散出库" }]; var r = n ? n.split("|") : [],
                    i = []; return t.allActionOptions.forEach(function(n) { r.indexOf(n.id) > -1 && i.push(n) }), g.getGroupProcurementMethod().then(function(n) { return n !== "group" || k.isRootGroup || (i = _.filter(i, function(n) { return n.id != c.OutOrderAction.ProcurementReturnOut })), t.baseData.outOrderActions = i, !0 }) })), t.consigneeDataSource = [], f.all(n) },
        ii = function() { if (t.currentInventoryOutOrder && t.currentInventoryOutOrder.items && t.currentInventoryOutOrder.items.length !== 0) { var n = _.pluck(t.currentInventoryOutOrder.items, "productId");
                t.getProductSalesPrice(n).then(function(n) { n && (_.each(t.currentInventoryOutOrder.items, function(t) { var i = _.find(n, function(n) { return n.productId === t.productId && n.salesPrice > 0 });
                        i && i.salesPrice && !t.businessPrice && (t.businessPrice = i.salesPrice, t.businessAmount = Ares.priceToFixed(t.outCount * t.businessPrice)) }), t.refreshTotalAmount()) }) } },
        at = function(n) { var i = f.defer(); return l.searchInventoryProductBatch({ includeZeroCount: !1, productIds: [n.productId], warehouseId: t.currentInventoryOutOrder.outWarehouseId }).success(function(t) { n.batches = t;
                i.resolve() }), i.promise },
        ri = function() { u.on("SKU_SELECT_ADD", function(n) { if (n && n.data) { var t = n.data.sku;
                    t && at(t).then(function() { ot(t, !1) }) } });
            u.on("TAB_SWITCHED", function() { if (t.currentInventoryOutOrder) { var n = _.pluck(t.currentInventoryOutOrder.items, "productId");
                    u.broadcast("SKU_EXIST_LIST", { productIds: n }) } }) };
    (function() { t.refreshTotalAmount = ft;
        t.removeSkuFromList = vt;
        t.save = wt;
        t.saveAndExecute = bt;
        t.getCurrentWarehouse = ct;
        t.getProductDealersByProductIds = ni;
        t.getProductSalesPrice = lt;
        t.addSkuToList = ot;
        t.getSkuBatches = at;
        t.getSkuListSalesPrices = ii;
        t.init = kt;
        ri() })() }]);
supplychainModule.directive("inventoryOutWarehouseOrderListView", ["$log", "$q", "$timeout", "$window", "$modal", "inventoryInOrderUtil", "loginContext", "supplyChainPrintUtil", "eventAggregator", "inventoryUtil", "moduleOptionProvider", function(n, t, i, r, u, f, e, o, s, h) { return { restrict: "E", templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-out-warehouse-order-list/inventory-out-warehouse-order-list-view.html", link: function(n, t) { "use strict"; var i = function() { var n = t.find(".in-out-warehouse-body-tbody");
                    n.height(angular.element(r).height() - 220) },
                c = function(n) { var t = n.id;
                    f.viewOperationLog(t, "InventoryOutOrder") },
                l = function(t) { var i = angular.copy(t);
                    o.printInventoryOutOrder(i, n) },
                a = function(n, t) { var i = n.productId || n.id;
                    s.publish(s.events.ProductSelected, i, t.delegateTarget) },
                v = function(t) { u.open({ animation: !0, backdrop: "static", template: "<inventory-out-order-batch-dialog-view><\/inventory-out-order-batch-dialog-view>", controller: "InventoryOutOrderBatchDialogCtrl", windowClass: "ares-medium-modal-content inventory-out-order-batch-dialog-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { orderItem: angular.copy(t), isOnlyShow: 1, isInventoryCostVisible: n.isInventoryCostVisible } } } }) },
                y = function() { h.getProductCodeOptions().then(function(t) { n.allowInsideCode = t.allowInsideCode }) },
                p = function(n) { return n && (n.outOrderAction == 5 || n.outOrderAction == 6) && !n.referenceOrderId };
            (function() { n.printOrder = l;
                n.viewOperationLog = c;
                n.onSelectProduct = a;
                i();
                n.showBatchItemDialog = v;
                n.isShowBizPrice = p;
                n.isInventoryCostVisible = e.isInventoryCostAllowed;
                y() })() } } }]);
supplychainModule.controller("inventoryOutWarehouseOrderListCtrl", ["$log", "$scope", "$q", "$filter", "inventorySvc", "aresNotification", "permissionProvider", "dataDicSvc", "dataHost", "inventoryUtil", "enums", "$modalInstance", "inventoryOutOrderUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a) { "use strict";
    t.states = [{ id: 0, name: "待处理" }, { id: 1, name: "已处理" }, { id: 2, name: "已作废" }]; var y = function() { var n = i.defer(); return o.warehouseDic.load().then(function(i) { t.warehouses = i;
                n.resolve(!0) }), n.promise },
        p = function() { var n = i.defer(); return o.userNameDic.load().then(function(i) { t.createUsers = i;
                n.resolve(!0) }), n.promise },
        w = function() { var n = i.defer(); return o.currentOfficeWorkProviderDic.load().then(function(i) { t.receivers = i;
                n.resolve(!0) }), n.promise },
        v = function() { b(s.outOrder) },
        b = function(r) { var e = i.defer(); return u.getOutOrder(r.id).success(function(n) { k(n);
                t.currentInventoryOrder = n;
                t.totalCount = 0;
                n.items && n.items.length > 0 && n.items.forEach(function(n) { t.totalCount += n.count });
                e.resolve(!0) }).error(function(t) { f.error("无法获取订单详情");
                n.log(t);
                e.reject() }), e.promise },
        k = function(n) { var i, u, r, f;
            n.warehouseId && (i = _.find(t.warehouses, function(t) { return t.id == n.warehouseId }), n.warehouseStr = i ? i.name : "", i && (u = e.getWarehousePermission(i), n.hasPermission = u));
            n.state != null && (r = _.find(t.states, function(t) { return t.id == n.state }), n.stateStr = r ? r.name : "");
            n.orderDate && (f = moment(n.orderDate).format("YYYY-MM-DD"), n.orderDateStr = f);
            d(n) },
        d = function(n) { var t = [],
                i = _.groupBy(n.items, "productId"),
                r = _.keys(i);
            angular.forEach(r, function(n) { var u = i[n],
                    r = { id: n, name: u[0].name, producer: u[0].producer, specification: u[0].specification, code: u[0].code, unit: u[0].unit, outCount: 0, price: 0, amount: 0, businessAmount: 0, businessPrice: 0, notes: u[0].notes, batches: u, isShowBatch: 0 },
                    f;
                angular.forEach(u, function(n) { r.outCount += n.count;
                    r.price += n.price;
                    r.amount += n.amount;
                    r.businessAmount += n.businessAmount;
                    (n.expiredDate || n.batchNumber) && (r.isShowBatch = 1) });
                f = Ares.priceToFixed(r.amount / r.outCount);
                r.price = r.price > f ? f : r.price;
                r.businessPrice = Ares.priceToFixed(r.businessAmount / r.outCount);
                t.push(r) });
            n.products = t },
        g = function() { l.dismiss("cancel") },
        nt = function() { return a.isPatientRequiredForOutOrder(t.currentInventoryOrder) };
    (function() { t.init = v;
        t.close = g;
        t.isPatientRequireForOrder = nt;
        y().then(function() { p().then(function() { w().then(function() { v() }) }) }) })() }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n() { this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/inventory/dialogs/inventory-pre-order-show-dialog/inventory-pre-order-show-dialog-view.html";
            this.link = function(n, t) { var i = function() { var r = t.find(".pre-order-container"),
                        u = t.find(".detail-list-head"),
                        f = t.find(".detail-list-body"),
                        e = t.find(".table-header"),
                        n = t.find(".table-main .table-main-content:visible"),
                        i = r.height() - u.height() - 70;
                    f.height(i);
                    n.height(i - e.height());
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } }) };
                n.calcHeight = i } } return n.$inject = [], n }();
    supplychainModule.directive("inventoryPreOrderShowDialogView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e) { t.order = i.order;
            t.currentType = i.type;
            t.orderType = r.InventoryOrderType;
            f.subscribe(t, f.events.IventoryOrderDetailRendered, function() { e(function() { t.calcHeight() }) });
            t.close = function() { u.close(i.type) } } return n.$inject = ["$q", "$scope", "host", "enums", "$modalInstance", "eventAggregator", "$timeout"], n }();
    supplychainModule.controller("InventoryPreOrderShowDialogCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryTransferOrderEditModalView", ["$log", "$q", "$window", "$rootScope", "eventAggregator", "$timeout", "$modal", "practiceSvc", "dataDicSvc", "enums", "warehouseUtil", "numberUtil", "aresConfirmDialog", "multiOfficeDataDic", "inventoryUtil", "aresTreeViewUtil", "loginContext", "warehouseSvc", "tenantOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b) { "use strict"; return { templateUrl: "/app/supplychain/views/inventory/dialogs/inventory-transfer-order-edit-modal/inventory-transfer-order-edit-modal-view.html", replace: !0, link: function(n, r) { var l = function() { r.find("#receiver-drop").kendoDropDownList({ dataSource: n.toProviders, dataValueField: "id", dataTextField: "name", filter: "contains", value: n.currentInventoryTransferOrder.receiverId, select: function(t) { var i = this.dataItem(t.item.index());
                            n.currentInventoryTransferOrder.receiverId = i.id } }) },
                p = function() { var i = t.defer(); return s.currentOfficeWorkProviderDic.load().then(function(t) { t.splice(0, 0, { id: 0, name: "请选择" });
                        n.providers = t;
                        r.find("#transferer-drop").kendoDropDownList({ dataSource: n.providers, dataValueField: "id", dataTextField: "name", filter: "contains", value: n.currentInventoryTransferOrder.transfererId, select: function(t) { var i = this.dataItem(t.item.index());
                                n.currentInventoryTransferOrder.transfererId = i.id } });
                        n.isAcrossOfficeInventoryTransferEnabled && n.currentInventoryTransferOrder.toOfficeId ? v.loadDic(n.currentInventoryTransferOrder.toOfficeId, "currentOfficeWorkProviderDic").then(function(t) { t.splice(0, 0, { id: 0, name: "请选择" });
                            n.toProviders = t || [];
                            f(function() { if (n.procurementApply) { var t = n.procurementApply.applicantId;
                                    t > 0 && (n.currentInventoryTransferOrder.receiverId = t) } l() });
                            i.resolve(!0) }) : (n.toProviders = angular.copy(n.providers), l(), i.resolve(!0)) }), i.promise },
                et = function() { var i = t.defer(); return n.isAcrossOfficeInventoryTransferEnabled && n.currentInventoryTransferOrder.toOfficeId ? b.searchWarehouses({ officeIds: [n.currentInventoryTransferOrder.toOfficeId], withOutOwner: !0 }).success(function(t) { t && (t = t.filter(function(n) { return !n.isInactive }));
                        n.toWarehouses = t || [];
                        i.resolve(!0) }) : (n.toWarehouses = angular.copy(n.allWarehouses), i.resolve(!0)), i.promise },
                k = function() { var t = r.find("#toWarehouse").data("kendoDropDownList"),
                        i, u;
                    t && n.toWarehouses.length > 0 && (t.dataSource.data(n.toWarehouses), i = _.find(n.toWarehouses, { isDefault: !0 }), u = i ? i.id : n.toWarehouses && n.toWarehouses.length > 0 ? n.toWarehouses[0].id : 0, t.value(u), n.currentInventoryTransferOrder.toWarehouseId = u, n.updateToWarehouseCount()) },
                d = function() { var t = r.find("#receiver-drop").data("kendoDropDownList"),
                        i, u;
                    t && (t.dataSource.data(n.toProviders), i = _.find(n.toProviders, { id: n.currentInventoryTransferOrder.receiverId }), u = i ? i.id : n.toProviders && n.toProviders.length > 0 ? n.toProviders[0].id : 0, t.value(u), n.currentInventoryTransferOrder.receiverId = u) },
                g = function() { var u = n.getCurrentWarehouseId(),
                        t, i;
                    r.find("#fromWarehouse").kendoDropDownList({ dataTextField: "name", dataValueField: "id", value: u, dataSource: n.warehouses, select: function(t) { var e = t.item.context.innerText,
                                u = _.find(n.warehouses, { name: e }),
                                i, r; if (u.grade === h.WarehouseGrade.Consignee.value) { t.preventDefault();
                                a.warn({ message: "不能对寄售仓库进行调拨操作" }); return } if (i = u.id, r = $("#fromWarehouse").data("kendoDropDownList"), n.isFromProcurementApply) { n.currentInventoryTransferOrder.items = [];
                                f(function() { n.addProductsFromProcurementApply() });
                                r.value(i);
                                c(i); return } n.currentInventoryTransferOrder && n.currentInventoryTransferOrder.items && n.currentInventoryTransferOrder.items.length > 0 && (t.preventDefault(), a.confirm({ message: "切换调拨仓库将清空调拨物品列表，确认切换吗？" }).then(function() { n.currentInventoryTransferOrder.items = [];
                                r.value(i);
                                c(i);
                                n.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: [] }) })) }, change: function(n) { var t = n.sender.value();
                            c(t) } });
                    t = _.find(n.toWarehouses, { isDefault: !0 });
                    i = t ? t.id : n.toWarehouses && n.toWarehouses.length > 0 ? n.toWarehouses[0].id : 0;
                    r.find("#toWarehouse").kendoDropDownList({ dataSource: n.toWarehouses, dataTextField: "name", dataValueField: "id", value: n.currentInventoryTransferOrder.toWarehouseId || i, select: function(t) { var i = this.dataItem(t.item); if (i.grade === h.WarehouseGrade.Consignee.value) { t.preventDefault();
                                a.warn({ message: "不能对寄售仓库进行调拨操作" }); return } n.currentInventoryTransferOrder.toWarehouseId = i[this.options.dataValueField] || null;
                            n.updateToWarehouseCount() } }) },
                c = function(t) { n.currentInventoryTransferOrder.fromWarehouseId = t * 1;
                    n.$modalInstance.broadcast("WAREHOUSE_ID_CHANGE", { warehouseId: n.currentInventoryTransferOrder.fromWarehouseId }) },
                nt = function(n, t) { var i = n.productId || n.id;
                    u.publish(u.events.ProductSelected, i, t.delegateTarget);
                    Ares.retainOnePopover() },
                tt = function(n) { var t = e.open({ animation: !0, backdrop: "static", template: "<transfer-order-item-batch-view><\/transfer-order-item-batch-view>", controller: "TransferOrderItemBatchCtrl", windowClass: "ares-medium-modal-content product-batch-wider", resolve: { host: function() { return { orderItem: angular.copy(n), isEditCount: 1 } } } });
                    t.result.then(function(t) { t && (n.batches = t.batchs, n.outCount = t.outCount); var i = r.find(".sku-auto-complete-selector-view").find("input");
                        i.length > 0 && i.focus() }) },
                o = r.find(".table-main-content"),
                y = function() { var r = angular.element(i).height(),
                        t = r - 315;
                    n.uiState.isShowSkuSelector || (t += 35);
                    o.height(t);
                    o.data("mCustomScrollbarIndex") ? o.mCustomScrollbar("update") : o.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) },
                it = function() { var u = r.find("#transferer-drop").data("kendoDropDownList"),
                        t, i;
                    u && (n.currentInventoryTransferOrder.transfererId = u.value());
                    t = r.find("#receiver-drop").data("kendoDropDownList");
                    t && (n.currentInventoryTransferOrder.receiverId = t.value());
                    i = r.find("#orderDateInput").data("kendoDatePicker");
                    i && (n.currentInventoryTransferOrder.orderDate = moment(i.value()).format("YYYY-MM-DD")) },
                rt = function(t) { var i = t.sender.value();
                    i == 0 ? (n.toWarehouses = angular.copy(n.warehouses), n.toProviders = angular.copy(n.providers)) : (n.toWarehouses = [{ id: 0, name: "请选择" }], n.toProviders = [{ id: 0, name: "请选择" }]);
                    n.selectedOfficeIdsArray = [];
                    n.currentInventoryTransferOrder.toWarehouseId = 0;
                    n.currentInventoryTransferOrder.receiverId = 0;
                    n.setToWarehouseDropDownDataSource();
                    n.setToProviderDropDownDataSource();
                    n.currentInventoryTransferOrder.toOfficeId = null },
                ut = function() { n.uiState.isShowSkuSelector = n.currentInventoryTransferOrder.inOrderAction != h.InOrderAction.PurchaseIn && (n.currentInventoryTransferOrder.state == 0 || !n.currentInventoryTransferOrder.id) },
                ft = function(n, t) { f(function() { var i, u; if (t) i = o.find("tr:first").find("input:first"), i.focus(), angular.isFunction(i[0].select) && i[0].select();
                        else { if (!n || n.keyCode !== 13) return;
                            u = r.find(".sku-auto-complete-selector-view").find("input");
                            u.length > 0 && u.focus() } }, 0, !1) };
            (function() { n.showBatchItemDialog = tt;
                n.onSelectedProduct = nt;
                n.setSaveData = it;
                n.setToWarehouseDropDownDataSource = k;
                n.setToProviderDropDownDataSource = d;
                n.onChangeTransferType = rt;
                n.initScrollBar = y;
                n.focusNextInput = ft;
                n.uiState = { currentSkuNotes: "", isShowSkuSelector: !0 };
                n.skuAutoCompleteOptions = { mode: "outOrder", isLinkedCare: null };
                n.initBaseData().then(function() { n.initCurrentInventoryTransferOrder(w.providerId).then(function() { n.initToWarehouses().then(function() { g();
                            ut();
                            p();
                            f(function() { y() }, 0, !1);
                            n.isFromProcurementApply && (n.currentInventoryTransferOrder.toWarehouseId = n.toWarehouses && n.toWarehouses.length > 0 ? n.toWarehouses[0].id : 0, n.addProductsFromProcurementApply()) }) }) }) })() } } }]);
supplychainModule.controller("InventoryTransferOrderEditModalCtrl", ["$log", "$scope", "$rootScope", "$modalInstance", "$q", "$modal", "$document", "officeOptionSvc", "aresNotification", "enums", "inventoryProductSvc", "productSvc", "inventorySvc", "host", "eventAggregator", "inventoryInOrderUtil", "$timeout", "warehouseUtil", "loginContext", "inventoryUtil", "officeSvc", "officeSelectorUtil", "moduleOptionProvider", "multiOfficeDataDic", "warehouseSvc", "tenantOptionSvc", "dataDicSvc", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt, ut, ft, et) { "use strict"; var st = function(n, i, r) { if (t.currentInventoryTransferOrder.items && t.currentInventoryTransferOrder.items.length > 200) { s.error("此调拨单已达到最大物品种类200个，无法继续添加。"); return } w(function() { var u = angular.copy(n),
                    f, o, e; if (u != null) { if (f = _.find(t.currentInventoryTransferOrder.items, function(n) { return n.productId == u.productId }), f) { if (i === "barcode") f.isSingleBatche ? f.outCount < f.inventoryCount ? f.outCount++ : s.error("此物品数量已与当前仓库的库存数量相同") : t.showBatchItemDialog(f);
                        else if (i === "unicode") e = _.find(f.batches, function(n) { return n.unicode === r }), e && (e.outCount === 1 ? s.info("该唯一码对应的批次已添加") : (e.outCount = 1, f.outCount = _.reduce(f.batches, function(n, t) { return n + (t.outCount || 0) }, 0), s.success("该唯一码批次添加成功")));
                        else { s.error("此物品已经在调拨物品列表中！"); return } return } t.currentInventoryTransferOrder.items = t.currentInventoryTransferOrder.items || [];
                    o = 0;
                    angular.forEach(u.batches, function(n) { n.id = 0;
                        n.inventoryCount = n.count;
                        o += n.count });
                    u.isSingleBatche = u.batches.length === 1;
                    u.outCount = angular.isDefined(u.applyCount) ? u.isSingleBatche ? u.applyCount >= o ? o : u.applyCount : 0 : u.isSingleBatche ? 1 : 0;
                    u.inventoryCount = o;
                    u.amount = 0;
                    t.currentInventoryTransferOrder.items.splice(0, 0, u);
                    i === "unicode" ? (e = _.find(u.batches, function(n) { return n.unicode === r }), e && (e.outCount = 1, u.outCount = _.reduce(u.batches, function(n, t) { return n + (t.outCount || 0) }, 0), s.success("该唯一码批次添加成功"))) : t.currentInventoryTransferOrder.items[0].isSingleBatche || t.isFromProcurementApply || t.showBatchItemDialog(t.currentInventoryTransferOrder.items[0]);
                    t.$modalInstance.broadcast("SKU_SELECT_ADDED", { productId: u.productId });
                    ot([u.productId]);
                    w(function() { t.initScrollBar();
                        i || w(function() { t.focusNextInput(null, !0) }, 0, !1) }, 0, !1) } }) },
        yt = function(n, i) { t.currentInventoryTransferOrder && t.currentInventoryTransferOrder.items && (n < 0 || n > t.currentInventoryTransferOrder.items.length || (t.currentInventoryTransferOrder.items.splice(n, 1), r.broadcast("SKU_SELECT_REMOVED", { productId: i.productId }), w(function() { t.initScrollBar() }, 0, !1))) },
        ht = function() { var n, i; return t.currentInventoryTransferOrder.toOfficeId == k.officeId ? "跨机构调拨收入单位不能是当前机构！" : t.currentInventoryTransferOrder.orderType == 1 && !t.currentInventoryTransferOrder.toOfficeId ? "请选择收入单位！" : t.currentInventoryTransferOrder.items && t.currentInventoryTransferOrder.items.length > 0 ? (n = _.find(t.currentInventoryTransferOrder.items, function(n) { return n.outCount === 0 || n.outCount == null }), n) ? "物品【" + n.name + "】数量必须大于0！" : (n = _.find(t.currentInventoryTransferOrder.items, function(n) { return n.outCount > n.count }), n) ? "物品【" + n.name + "】库存数不足！" : t.currentInventoryTransferOrder.fromWarehouseId <= 0 ? "请选择调出仓库 ！" : t.currentInventoryTransferOrder.toWarehouseId <= 0 ? "请选择调入仓库 ！" : (i = _.find(t.warehouses, function(n) { return n.grade == h.WarehouseGrade.Consignee.value && (n.id == t.currentInventoryTransferOrder.fromWarehouseId || n.id == t.currentInventoryTransferOrder.toWarehouseId) }), i) ? "不能对寄售仓库进行调拨操作 ！" : t.currentInventoryTransferOrder.fromWarehouseId == t.currentInventoryTransferOrder.toWarehouseId ? "调出仓库与调入仓库不能相同 ！" : (t.setSaveData(), !d.checkOrderDateValid(t.currentInventoryTransferOrder.orderDate)) ? "请输入单据日期 ！" : d.checkOrderGreaterThanToday(t.currentInventoryTransferOrder.orderDate) ? "单据日期不能大于当前日期 ！" : t.currentInventoryTransferOrder.transfererId <= 0 ? "请选择发货人 ！" : t.currentInventoryTransferOrder.receiverId <= 0 ? "请选择收货人！" : t.currentInventoryTransferOrder.transfererId == t.currentInventoryTransferOrder.receiverId <= 0 ? "发货人与收货人不能相同！" : "" : "请添加调拨物品!" },
        ct = function() { var i = t.currentInventoryTransferOrder.transfererId > 0 ? t.currentInventoryTransferOrder.transfererId : null,
                r = t.currentInventoryTransferOrder.receiverId > 0 ? t.currentInventoryTransferOrder.receiverId : null,
                n = { id: t.currentInventoryTransferOrder.id, fromWarehouseId: t.currentInventoryTransferOrder.fromWarehouseId, toWarehouseId: t.currentInventoryTransferOrder.toWarehouseId, orderNumber: t.currentInventoryTransferOrder.orderNumber, orderDate: t.currentInventoryTransferOrder.orderDate, notes: t.currentInventoryTransferOrder.notes, state: t.currentInventoryTransferOrder.state, transfererId: i, receiverId: r, orderType: t.currentInventoryTransferOrder.orderType, toOfficeId: t.currentInventoryTransferOrder.toOfficeId, items: pt() }; return t.isFromProcurementApply && (n.procurementApplyOrderId = t.procurementApply.id), n },
        pt = function() { var n = []; return angular.forEach(t.currentInventoryTransferOrder.items, function(i) { angular.forEach(i.batches, function(r) { i.batches.length == 1 && (r.outCount = i.outCount);
                    n.push({ name: i.name, productId: i.productId, batchNumber: r.batchNumber, expiredDate: r.expiredDate, unicode: r.unicode, count: r.outCount, price: r.price, notes: i.notes, code: i.code, unit: i.unit, producer: i.producer, state: t.currentInventoryTransferOrder.state, specification: i.specification }) }) }), n },
        lt = function() { var n = ct(),
                i = u.defer(),
                r = ht(); return r ? (et.warn({ message: r }), i.reject()) : (t.currentInventoryTransferOrder.orderDate || (t.currentInventoryTransferOrder.orderDate = moment(Ares.today()).format("YYYY-MM-DD")), n = ct(), n.id == -1 || n.id == null || n.id == 0 ? a.addTransferOrder(n).success(function(n) { t.currentInventoryTransferOrder.id = n.id;
                i.resolve(!0) }).error(function(n) { d.showInventoryErrorMessage(n, "保存失败");
                i.reject() }) : a.updateTransferOrder(n).success(function() { i.resolve(!0) }).error(function(n) { d.showInventoryErrorMessage(n, "保存失败");
                i.reject() })), i.promise },
        wt = function(n) { return Ares.priceToFixed(n) },
        bt = function() { Ares.ensureNotDuplicated("SaveInventoryTransferOrder") && lt().then(function() { t.currentInventoryTransferOrder.state == 0 && (y.publish(y.events.RefreshIventoryHint, null, "InventoryTransferOrderEditCtrl"), y.publish(y.events.IventoryTransferOrderCreated, t.currentInventoryTransferOrder, "InventoryCheckEditCtrl"));
                s.success("保存成功");
                r.close(t.currentInventoryTransferOrder) }) },
        kt = function() { if (Ares.ensureNotDuplicated("SaveAndExecuteInventoryTransferOrder")) { var n = ht();
                n ? et.warn({ message: n }) : t.currentInventoryTransferOrder.orderType == 1 ? at() : et.warn({ message: "您确定执行该单据吗？单据执行后库存将发生变更", onConfirm: function() { at() }, onCancel: function() {} }) } },
        at = function() { lt().then(function() { dt(); var n = "保存并执行";
                t.currentInventoryTransferOrder.id == -1 || t.currentInventoryTransferOrder.id == null || (n = "编辑");
                Ares.sensors.track("InventoryOperation", { OrderNumber: t.currentInventoryTransferOrder.orderNumber, OperationType: "调拨", OperationMode: n }) }) },
        dt = function() { a.approveTransferOrder(t.currentInventoryTransferOrder.id).success(function() { y.publish(y.events.RefreshIventoryHint, null, "InventoryTransferOrderEditCtrl");
                t.currentInventoryTransferOrder.state = 1;
                r.close(t.currentInventoryTransferOrder);
                s.success("调拨成功!") }).error(function(n) { n.name === "InventoryOperationException" || n.name === "NotInOrderInformationException" ? (t.isDisableSaveBtn = !1, et.warn({ message: n.message })) : (s.error("调拨失败!"), t.isDisableSaveBtn = !1) }) },
        gt = function(n) { n = n < 0 ? 0 : n; var i = u.defer(),
                f = moment(Ares.today()).format("YYYY-MM-DD"),
                r = vt(); return t.isFromProcurementApply = v.isFromProcurementApply, t.procurementApply = v.procurementApply, t.currentInventoryTransferOrder = { state: 0, amount: 0, consigneeType: -1, orderDate: f, fromWarehouseId: r, toWarehouseId: r, transfererId: n, receiverId: n, id: v.orderId || null }, t.isAcrossOfficeInventoryTransferEnabled && (t.currentInventoryTransferOrder.orderType = 0), t.isFromProcurementApply && (t.currentInventoryTransferOrder.orderType = 1, t.currentInventoryTransferOrder.toOfficeId = t.procurementApply.officeId), t.currentInventoryTransferOrder.id > 0 && t.currentInventoryTransferOrder.id != null ? ni(t.currentInventoryTransferOrder.id).then(function() { i.resolve(!0) }) : i.resolve(!0), i.promise },
        ni = function(i) { var r = u.defer(); return a.getTransferOrder(i).success(function(n) { var i; if (n) { i = { id: n.id, fromWarehouseId: n.fromWarehouseId, toWarehouseId: n.toWarehouseId, orderNumber: n.orderNumber, orderDate: n.orderDate, notes: n.notes, state: n.state, transfererId: n.transfererId, receiverId: n.receiverId, toOfficeId: n.toOfficeId, orderType: n.orderType, items: [] };
                    i.toOfficeId && (it.loadDic(i.toOfficeId, "currentOfficeWorkProviderDic"), t.selectedOfficeIdsArray = [i.toOfficeId]); var f = angular.copy(n.items),
                        u = _.groupBy(f, "productId"),
                        e = _.keys(u);
                    angular.forEach(e, function(n) { var t = u[n],
                            r = [],
                            f = 0,
                            e = 0,
                            o;
                        angular.forEach(t, function(n) { n.outCount = n.count;
                            f += n.inventoryCount;
                            e += n.outCount;
                            r.push(n) });
                        o = { productId: n, name: t[0].name, specification: t[0].specification, unit: t[0].unit, producer: t[0].producer, isSingleBatche: r.length === 1, batches: r, inventoryCount: f, outCount: e, notes: t[0].notes };
                        i.items.push(o) });
                    t.currentInventoryTransferOrder = i;
                    ot();
                    r.resolve(!0) } }).error(function(t) { s.error("无法获取订单详情");
                n.log(t);
                r.reject() }), r.promise },
        vt = function() { var n = null,
                r, u; return t.warehouses && t.warehouses.length > 0 && (n = t.warehouses[0].id || null, r = b.getDefaultWarehouse(t.warehouses), n = r ? r.id : n), n = i.currentWarehouseId > 0 ? i.currentWarehouseId : n, n = v.fromWarehouseId ? v.fromWarehouseId : n, n = t.currentInventoryTransferOrder && t.currentInventoryTransferOrder.fromWarehouseId ? t.currentInventoryTransferOrder.fromWarehouseId : n, u = _.find(t.warehouses, function(t) { return t.id === n }), u.grade === h.WarehouseGrade.Consignee.value && (n = _.find(t.warehouses, function(n) { return n.grade !== h.WarehouseGrade.Consignee.value }).id), n },
        ot = function(n) { var f = u.defer(),
                e = t.currentInventoryTransferOrder.toWarehouseId,
                i = !1,
                r; return n || (n = _.pluck(t.currentInventoryTransferOrder.items, "productId"), i = !0), r = { warehouseId: e, productIds: n }, c.getInventoryProductsCount(r).success(function(r) { _.each(t.currentInventoryTransferOrder.items, function(t) { i ? t.inInventoryCount = r[t.productId] || 0 : n.indexOf(t.productId) > -1 && (t.inInventoryCount = r[t.productId] || 0) }) }), f.promise },
        ti = function(n) { t.currentInventoryTransferOrder.toOfficeId = n[0].id;
            t.selectedOfficeIdsArray = [t.currentInventoryTransferOrder.toOfficeId];
            rt.searchWarehouses({ officeIds: t.selectedOfficeIdsArray, withOutOwner: !0 }).success(function(n) { n && (n = n.filter(function(n) { return !n.isInactive }));
                t.toWarehouses = n || [];
                t.setToWarehouseDropDownDataSource() });
            it.loadDic(t.currentInventoryTransferOrder.toOfficeId, "currentOfficeWorkProviderDic").then(function(n) { t.toProviders = n || [];
                t.setToProviderDropDownDataSource() }) },
        ii = function() { var n = {},
                i = [];
            _.each(t.procurementApply.items, function(t) { i.push(t.productId);
                n[t.productId] = _.clone(t) });
            c.searchInventoryProduct({ productIds: i, warehouseId: t.currentInventoryTransferOrder.fromWarehouseId, pageSize: i.length, pageIndex: 1 }).success(function(i) { _.each(i.page.items, function(i) { var r = n[i.productId];
                    i.applyCount = r.count - r.handledCount < 0 ? 0 : r.count - r.handledCount;
                    i.name = i.product.name;
                    i.specification = i.product.specification;
                    i.unit = i.product.unit;
                    t.addProductToList(i);
                    delete n[i.productId] });
                _.each(n, function(n) { n.applyCount = n.count - n.handledCount < 0 ? 0 : n.count - n.handledCount;
                    n.count = 0;
                    n.product = _.clone(n);
                    n.batches = [_.clone(n)];
                    t.addProductToList(n) }) }) },
        ri = function() { var n = []; return n.push(ut.getTenantOption("IsAcrossOfficeInventoryTransferEnabled").then(function(n) { t.isAcrossOfficeInventoryTransferEnabled = n;
                t.isAcrossOfficeInventoryTransferEnabled && g.getNodesInGroup().success(function(n) { t.officeTreeData = nt.setId(n) }) })), n.push(u.all([ft.warehouseDic.loadActive(), rt.searchWarehouses({ withOutOwner: !0 })]).then(function(n) { t.warehouses = b.filterWarehouses(n[0]);
                t.allWarehouses = b.filterWarehouses(n[1].data) })), n.push(ft.currentOfficeWorkProviderDic.load().then(function(n) { n.splice(0, 0, { id: 0, name: "请选择" });
                t.providers = n })), u.all(n) },
        ui = function() { var n = u.defer(); return t.isAcrossOfficeInventoryTransferEnabled && t.currentInventoryTransferOrder.toOfficeId ? rt.searchWarehouses({ officeIds: [t.currentInventoryTransferOrder.toOfficeId], withOutOwner: !0 }).success(function(i) { i && (i = i.filter(function(n) { return !n.isInactive }));
                t.toWarehouses = i || [];
                n.resolve(!0) }) : (t.toWarehouses = angular.copy(t.allWarehouses), n.resolve(!0)), n.promise },
        fi = function(n) { var i = u.defer(); return c.searchInventoryProductBatch({ includeZeroCount: !1, productIds: [n.productId], warehouseId: t.currentInventoryTransferOrder.fromWarehouseId }).success(function(t) { n.batches = t;
                i.resolve() }), i.promise },
        ei = function() { r.on("SKU_SELECT_ADD", function(n) { if (n && n.data) { var t = n.data.sku;
                    t && fi(t).then(function() { st(t, !1, !0) }) } });
            r.on("TAB_SWITCHED", function() { if (t.currentInventoryTransferOrder) { var n = _.pluck(t.currentInventoryTransferOrder.items, "productId");
                    r.broadcast("SKU_EXIST_LIST", { productIds: n }) } }) };
    (function() { t.removeProductFromList = yt;
        t.priceToFixed = wt;
        t.save = bt;
        t.saveAndExecute = kt;
        t.getCurrentWarehouseId = vt;
        t.onOfficeSelected = ti;
        t.addProductsFromProcurementApply = ii;
        t.initBaseData = ri;
        t.initCurrentInventoryTransferOrder = gt;
        t.initToWarehouses = ui;
        t.addProductToList = st;
        t.updateToWarehouseCount = ot;
        ei() })() }]);
supplychainModule.directive("inventoryCheckOrderListView", ["$log", "$q", "$timeout", "$window", "inventoryCheckOrderUtil", function(n, t, i, r, u) { return { replace: !0, templateUrl: "/app/supplychain/views/inventory/inventory-check-order-list/inventory-check-order-list-view.html", controller: "InventoryCheckOrderListCtrl", link: function(n, f) { var h = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } },
                c = function() { l();
                    e(); var t = angular.element(r);
                    t.on("resize", function() { e() });
                    n.initSearchCriteria();
                    u.initBasicData(n).then(function() { n.initBusinessData() }) },
                l = function() { n.uiState = { isShowAdvancedSearch: !1 };
                    n.searchDateRange = { startDate: "", endDate: "" };
                    n.page = { pageIndex: 1, pageSize: 20 };
                    n.state = 0;
                    n.kendoDatePickerOptions = { format: "yyyy-MM-dd", max: new Date } },
                e = function() { var u = angular.element(r).height(),
                        e = 110,
                        o, t;
                    n.uiState.isShowAdvancedSearch && (e = 242); var s = u - e - 145 - (window.Ares3 ? 10 : 0),
                        i = f.find(".left-side-container .table-main .table-main-content");
                    i.height(s);
                    i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar(h); var c = u - 130,
                        l = f.find(".right-side-container .detail-list");
                    l.height(c);
                    o = u - 300 - (window.Ares3 ? 10 : 0);
                    t = f.find(".right-side-container .table-main .table-main-content:visible");
                    t.height(o);
                    t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar(h) },
                s = function(r) { var u = t.defer(); return n.page.pageIndex = r ? n.page.pageIndex : 1, n.searchCheckOrderList().then(function() { i(function() { n.pageData.items[0] ? o(n.pageData.items[0], 0) : n.checkOrder = "";
                            u.resolve() }) }), u.promise },
                a = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && s() },
                o = function(t, i) { n.triggerIndex = i;
                    n.checkOrder = t },
                v = function(t) { var i = _.findIndex(n.pageData.items, { id: t }),
                        r;
                    i > -1 && n.pageData.items.length > 1 ? (r = i - 1, n.pageData.items.splice(i, 1), n.pageData.items.length > i ? o(n.pageData.items[i], i) : n.pageData.items.length > r && r > -1 && o(n.pageData.items[r], r)) : s() },
                y = function(t) { n.state = t;
                    n.checkOrder = null;
                    n.initSearchCriteria(t);
                    n.onSearchCheckOrderList() },
                p = function() { n.uiState.isShowAdvancedSearch = !n.uiState.isShowAdvancedSearch;
                    e() },
                w = function(t) { n.searchCriteria.startDate = t.startDate;
                    n.searchCriteria.endDate = t.endDate;
                    n.onSearchCheckOrderList() };
            (function() { n.onSearchCheckOrderList = s;
                n.toggleAdvancedSearch = p;
                n.onDateRangeChanged = w;
                n.selectedNextOrder = v;
                n.checkOrderDetail = o;
                n.initTableView = e;
                n.switchState = y;
                n.onEnter = a;
                n.isAres3 = window.Ares3;
                c() })() } } }]);
supplychainModule.controller("InventoryCheckOrderListCtrl", ["$log", "$q", "$rootScope", "eventAggregator", "$scope", "inventorySvc", "reportUtil", function(n, t, i, r, u, f, e) { "use strict"; var h = function() { s().then(function() { u.menuChangedData || (u.pageData.items[0] ? u.checkOrderDetail(u.pageData.items[0], 0) : u.switchState(1));
                u.initTableView() }) },
        c = function(n) { n ? u.searchCriteria.state = n : u.searchCriteria = { state: 0, orderNumber: null, createdUserId: 0, operatorId: 0 };
            l(n || 0);
            u.searchCriteria.startDate = u.searchDateRange.startDate;
            u.searchCriteria.endDate = u.searchDateRange.endDate },
        l = function(n) { if (n === 0) u.searchDateRange = { startDate: "", endDate: "" };
            else { var t = e.getDefaultTimeSpan();
                u.searchDateRange = { startDate: u.searchDateRange.startDate || moment(t.startTime).format("YYYY-MM-DD"), endDate: u.searchDateRange.endDate || moment(t.endTime).format("YYYY-MM-DD") } } },
        s = function() { var n = t.defer(); return f.searchPreCheckOrder(a()).success(function(t) { u.pageData = t.page ? t.page : t;
                u.page.totalCount = u.pageData.totalCount;
                u.page.pageCount = u.pageData.pageCount || 1;
                n.resolve() }), n.promise },
        a = function() { var n = angular.copy(u.searchCriteria); return n.pageIndex = u.page.pageIndex, n.pageSize = u.page.pageSize, n.warehouseId = i.currentWarehouseId != 0 ? i.currentWarehouseId : null, n.operatorId && n.operatorId !== "0" || (n.operatorId = null), n.createdUserId && n.createdUserId !== "0" || (n.createdUserId = null), n.startDate = moment(n.startDate).format("YYYY-MM-DD"), n.endDate = moment(n.endDate).add(1, "days").format("YYYY-MM-DD"), n },
        o = function(n) { u.menuChangedData = n;
            u.switchState(n.state);
            u.checkOrderDetail(n, null) },
        v = function() { r.subscribe(u, r.events.IventoryCheckOrderCreated, function(n, t) { o(t) });
            r.subscribe(u, r.events.IventoryActionMenuChanged, function(n, t) { o(t) });
            r.subscribe(u, r.events.GlobalWarehouseChanged, function() { u.onSearchCheckOrderList() });
            r.subscribe(u, r.events.IventoryOrderDetailRendered, function() { u.initTableView() }) };
    (function() { u.searchCheckOrderList = s;
        u.initSearchCriteria = c;
        u.initBusinessData = h;
        u.positioningTab = o;
        v() })() }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r) { var u = this;
            this.eventAggregator = n;
            this.aresModalShelf = t;
            this.inventoryInOrderUtil = i;
            this.supplyChainPrintUtil = r;
            this.restrict = "E";
            this.replace = !0;
            this.scope = { order: "=", state: "=" };
            this.templateUrl = "/app/supplychain/views/inventory/inventory-check-order-list/components/inventory-check-order-detail-view.html";
            this.controller = "InventoryCheckOrderDetailCtrl";
            this.link = function(n) { var t = u,
                    r = function(n, i) { var r = n.productId;
                        t.eventAggregator.publish(t.eventAggregator.events.ProductSelected, r, i.delegateTarget) },
                    f = function(n) { t.inventoryInOrderUtil.viewOperationLog(n.id, "InventoryCheckOrder") },
                    e = function(i) { if (i) { var r = angular.copy(i);
                            t.supplyChainPrintUtil.printInventoryCheckOrder(r, n) } },
                    o = function() { i().then(function() { n.$parent.onSearchCheckOrderList ? n.$parent.onSearchCheckOrderList() : n.$parent.close() }) },
                    s = function() { i(!0).then(function(t) { n.$parent.switchState ? n.$parent.switchState(t.state) : n.$parent.close() }) },
                    i = function(i) { var r = t.aresModalShelf.open({ title: i ? "新建盘点单" : "编辑盘点单", titleIconClass: "iconfont icon-pandian", template: "<inventory-check-order-edit-modal-view><\/inventory-check-order-edit-modal-view>", controller: "InventoryCheckOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { isCopyToNew: i, orderId: n.currentInventoryCheckOrder.id, checker: _.find(n.providers, { id: n.currentInventoryCheckOrder.checkerId }), warehouse: { id: n.currentInventoryCheckOrder.warehouseId, name: n.currentInventoryCheckOrder.warehouseName } } } } }); return r.result };
                (function() { n.viewOperationLog = f;
                    n.onSelectedProduct = r;
                    n.printCheckOrder = e;
                    n.onEditOrder = o;
                    n.onCopyOrder = s })() } } return n.$inject = ["eventAggregator", "aresModalShelf", "inventoryInOrderUtil", "supplyChainPrintUtil"], n }();
    supplychainModule.directive("inventoryCheckOrderDetailView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h) { var c = function(r) { var f = t.defer(); return o.getCheckOrder(r).success(function(n) { h.formatOrder(n, i);
                        i.currentInventoryCheckOrder = n;
                        f.resolve(!0) }).error(function(t) { u.error("无法获取订单详情");
                        n.log(t);
                        f.reject() }), f.promise },
                v = function() { Ares.ensureNotDuplicated("InventoryCheckOrderApproveCheck") && f.confirm({ message: "您确定执行该单据吗？单据执行后库存将发生变更" }).then(function() { o.approveCheckOrder(i.currentInventoryCheckOrder.id).success(function() { u.success("操作成功!");
                            l("执行", !0);
                            i.$parent.selectedNextOrder ? i.$parent.selectedNextOrder(i.currentInventoryCheckOrder.id) : i.$parent.close() }).error(function(n) { s.showInventoryErrorMessage(n, "操作失败") }) }) },
                y = function() { if (Ares.ensureNotDuplicated("InventoryCheckOrderCancelCheck")) { var n = i.currentInventoryCheckOrder.id;
                        f.confirm({ message: "该单据已关联其他单据，作废后相关单据也会被作废，是否确定作废" }).then(function() { o.cancelCheckOrder(n).success(function() { if (u.success("作废成功!"), l("作废", i.currentInventoryCheckOrder.state === 0), i.$parent.positioningTab) { var t = { id: n, state: 2 };
                                    i.$parent.positioningTab(t) } else i.$parent.close() }).error(function(n) { s.showInventoryErrorMessage(n, "作废失败") }) }) } },
                l = function(n, t) { t && e.publish(e.events.RefreshIventoryHint, null, "InventoryCheckOrderDetailCtrl");
                    Ares.sensors.track("InventoryOperation", { OrderNumber: i.currentInventoryCheckOrder.orderNumber, OperationType: "盘点", OperationMode: n }) },
                p = function(n) { var e, h, c; if (n) { var u = angular.copy(n),
                            f = w(u),
                            t = [],
                            o = { columnSettings: [70, 90, 150, 60, 200, 60, 80, 80, 100, 100, 100, 200, 100], title: "盘点单" + u.orderNumber, fileName: "盘点单" + u.orderNumber, headerRow: { value: "库存盘点单", colSpan: 13 }, contentRow: [] };
                        o.contentRow.push({ row: [{ cellType: "headerCell", value: "机构名称：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: f.officeName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "盘点仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: u.warehouseName, colSpan: 8, textAlign: "left" }] });
                        o.contentRow.push({ row: [{ cellType: "headerCell", value: "盘点单号：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: u.orderNumber, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "单据日期：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: r("toDateString")(u.orderDate), colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "制单人：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: u.createUserStr, colSpan: 4, textAlign: "left" }] });
                        o.contentRow.push({ row: [{ cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: u.notes, colSpan: 12, textAlign: "left" }] });
                        t = [];
                        e = 0;
                        t.push({ cellType: "headerCell", value: "序号" });
                        e += 1;
                        i.productCodeOptions.allowInsideCode && (t.push({ cellType: "headerCell", value: "内部编码" }), e += 1);
                        h = 1 + (i.productCodeOptions.allowInsideCode ? 0 : 1);
                        t.push({ cellType: "headerCell", value: "名称", colSpan: h }, { cellType: "headerCell", value: "品牌" }, { cellType: "headerCell", value: "规格" }, { cellType: "headerCell", value: "单位" }, { cellType: "headerCell", value: "盘点前数量" }, { cellType: "headerCell", value: "盘点数量" }, { cellType: "headerCell", value: "盈亏数量" });
                        e += 6 + h;
                        f.isBatchNumberVisible && (t.push({ cellType: "headerCell", value: "批号" }), e += 1);
                        f.isExpireDateVisible && (t.push({ cellType: "headerCell", value: "有效期至" }), e += 1);
                        f.isUnicodeVisible && (t.push({ cellType: "headerCell", value: "唯一码" }), e += 1);
                        t.push({ cellType: "headerCell", value: "备注", colSpan: 13 - e });
                        o.contentRow.push({ row: t });
                        _.each(u.details, function(n, u) { t = [];
                            t.push({ cellType: "centerCell", value: u + 1 });
                            i.productCodeOptions.allowInsideCode && t.push({ cellType: "centerCell", value: n.code });
                            t.push({ cellType: "regularCell", value: n.name, colSpan: h });
                            t.push({ cellType: "regularCell", value: n.producer });
                            t.push({ cellType: "regularCell", value: n.specification });
                            t.push({ cellType: "centerCell", value: n.unit });
                            t.push({ cellType: "numberCell", value: n.inventoryCount });
                            t.push({ cellType: "numberCell", value: n.actualCount });
                            t.push({ cellType: "numberCell", value: n.actualCount - n.inventoryCount });
                            f.isBatchNumberVisible && t.push({ cellType: "centerCell", value: n.batchNumber });
                            f.isExpireDateVisible && t.push({ cellType: "centerCell", value: r("toDateString")(n.expiredDate) });
                            f.isUnicodeVisible && t.push({ cellType: "centerCell", value: n.unicode });
                            t.push({ cellType: "regularCell", value: n.notes, colSpan: 13 - e });
                            o.contentRow.push({ row: t }) });
                        t = [];
                        t.push({ cellType: "headerCell", value: "合计", colSpan: 6, textAlign: "left" });
                        t.push({ cellType: "numberCell", value: f.totalInventoryCount });
                        t.push({ cellType: "numberCell", value: f.totalActualCount });
                        t.push({ cellType: "numberCell", value: f.totalCountGap });
                        t.push({ cellType: "regularCell", value: "", colSpan: 4 });
                        o.contentRow.push({ row: t });
                        c = "盘点负责人：" + u.checkerStr + "            签字：";
                        o.contentRow.push({ row: [{ cellType: "regularCell", value: "", colSpan: 7 }, { cellType: "headerCell", value: c, colSpan: 6, textAlign: "left" }] });
                        s.exportExcel(o) } },
                w = function(n) { var t = {},
                        s;
                    n.officeId && (s = i.basicData.offices.find(function(t) { return t.id == n.officeId }), t.officeName = s.name); var r = 0,
                        u = 0,
                        f = !1,
                        e = !1,
                        o = !1; return n.details.forEach(function(n) { r += n.inventoryCount;
                        u += n.actualCount;
                        f = f || n.expiredDate;
                        e = e || n.batchNumber;
                        o = o || n.unicode }), t.totalInventoryCount = r, t.totalActualCount = u, t.totalCountGap = u - r, t.isExpireDateVisible = f, t.isBatchNumberVisible = e, t.isUnicodeVisible = o, t },
                a = function(n) { n ? c(n.id).then(function() { e.publish(e.events.IventoryOrderDetailRendered, null, "InventoryCheckOrderDetailCtrl") }) : i.currentInventoryCheckOrder = null };
            (function() { i.getOrderDetail = c;
                i.onApproveOrder = v;
                i.onCancelOrder = y;
                i.exportExcel = p;
                h.initBasicData(i).then(function() { a(i.order) });
                i.$watch("order", function(n) { a(n) }) })() } return n.$inject = ["$log", "$q", "$scope", "$filter", "aresNotification", "aresConfirmDialog", "eventAggregator", "inventorySvc", "inventoryUtil", "inventoryCheckOrderUtil"], n }();
    supplychainModule.controller("InventoryCheckOrderDetailCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryInOrderListView", ["$log", "$q", "$timeout", "$window", "enums", "inventoryInOrderUtil", function(n, t, i, r, u, f) { return { replace: !0, templateUrl: "/app/supplychain/views/inventory/inventory-in-order-list/inventory-in-order-list-view.html", controller: "InventoryInOrderListCtrl", link: function(n, e) { var h = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } },
                a = function() { o(); var n = angular.element(r);
                    n.on("resize", function() { o() }) },
                c = function() { var u = angular.element(r).height(),
                        i = 154;
                    n.uiState.showAdvancedSearch ? i = 374 : n.state !== 0 && (i -= 44); var f = u - i - 155 - (window.Ares3 ? 30 : 0),
                        t = e.find(".left-side-container .table-main .table-main-content");
                    t.height(f);
                    t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar(h) },
                o = function() { c(); var r = e.find(".right-side-container .detail-list"),
                        n = e.find(".right-side-container .detail-list .detail-list-head"),
                        t = e.find(".right-side-container .detail-list .detail-list-body"),
                        u = e.find(".right-side-container .detail-list .detail-footer"),
                        f = e.find(".right-side-container .detail-list .detail-list-body .table-header");
                    i(function() { var o = r.height() - n.height() - u.height() - parseInt(n.css("margin-top")) - parseInt(n.css("margin-bottom")) - parseInt(t.css("margin-top")) - parseInt(t.css("margin-bottom")) - f.height() - 20,
                            i = e.find(".right-side-container .table-main .table-main-content:visible");
                        i.height(o);
                        i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar(h) }) },
                v = function(t) { n.searchDateRange.startDate = t.startDate;
                    n.searchDateRange.endDate = t.endDate;
                    n.onSearchInOrderList() },
                s = function(r) { var u = t.defer(); return n.page.pageIndex = r ? n.page.pageIndex : 1, n.searchInOrderList().then(function() { n.pageData.items[0] ? l(n.pageData.items[0], 0) : n.order = "";
                        i(function() { o();
                            u.resolve() }) }), u.promise },
                y = function() { n.deliverDataSource = n.searchCriteria.deliverType == u.InOrderDeliverType.Provider ? n.basicData.providers : n.searchCriteria.deliverType == u.InOrderDeliverType.Operatory ? n.basicData.operatories : n.searchCriteria.deliverType == u.InOrderDeliverType.Department ? n.basicData.departments : [{ name: "请选择", value: "" }];
                    n.searchCriteria.deliver = "请选择";
                    n.onSearchInOrderList() },
                p = function(n) { var t = window.event ? n.keyCode : n.which;
                    t === 13 && s() },
                l = function(t, i) { n.triggerIndex = i;
                    n.order = t },
                w = function(t) { n.state !== t && (n.state = t, n.initSearchData(), n.inOrderActionOptions = t === 0 ? n.inOrderActionSearchTypes.pending : n.inOrderActionSearchTypes.other, _.some(n.inOrderActionOptions, function(t) { return t.value === n.searchCriteria.inOrderAction }) || (n.searchCriteria.inOrderAction = "all"), n.order = null, s(), i(function() { c() })) },
                b = function() { n.uiState.showAdvancedSearch = !n.uiState.showAdvancedSearch;
                    o() };
            (function() { n.uiState = { showAdvancedSearch: !1, deliverType: { onChange: y } };
                n.state = 0;
                n.page = { pageIndex: 1, pageSize: 20 };
                n.isAres3 = window.Ares3;
                n.switchState = w;
                n.showInOrderDetail = l;
                n.onSearchInOrderList = s;
                n.onEnter = p;
                n.initTableView = o;
                n.toggleAdvancedSearch = b;
                n.onDateRangeChanged = v;
                a();
                n.initSearchData();
                f.initBaseData(n).then(function() { n.checkShowCertainInOrder();
                    n.initDefaultData() }) })() } } }]);
supplychainModule.controller("InventoryInOrderListCtrl", ["$scope", "$q", "$rootScope", "$timeout", "eventAggregator", "inventorySvc", "loginContext", "reportUtil", "$stateParams", "inventoryInOrderUtil", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var l = function() { var r = angular.copy(n.searchCriteria),
                u, e; return r.pageIndex = n.page.pageIndex, r.pageSize = n.page.pageSize, u = n.state, r.operatorId && r.operatorId != "0" || (r.operatorId = null), r.dealer = r.dealer === "所属供应商" ? "" : r.dealer, r.receiverId && r.receiverId != "0" || (r.receiverId = null), r.purchaserId && r.purchaserId != "0" || (r.purchaserId = null), r.inOrderAction === "all" && (r.inOrderAction = null), r.waybillNo === "" && (r.waybillNo = null), r.deliver !== "请选择" && r.deliver || (r.deliver = null), r.startDate = n.searchDateRange.startDate, r.endDate = moment(n.searchDateRange.endDate).isValid() ? moment(n.searchDateRange.endDate).add(1, "d").format("YYYY-MM-DD") : "", r.warehouseId = i.currentWarehouseId != 0 ? i.currentWarehouseId : null, e = t.defer(), u ? (r.waybillNo = "", r.state = u) : (r.createdUserId = r.operatorId, r.operatorId = r.receiverId, r.orderAction = r.inOrderAction), f.searchInOrder(r, u).success(function(t) { n.pageData = t.page ? t.page : t;
                n.page.totalCount = n.pageData.totalCount;
                n.page.pageCount = n.pageData.pageCount || 1;
                angular.forEach(n.pageData.items, function(t) { h.setOrderProperties(t, n) });
                e.resolve() }), e.promise },
        a = function() { v();
            l().then(function() { r(function() { if (n.menuChangedData) { if (n.menuChangedData && n.menuChangedData.id) { var t = 0,
                                i = _.find(n.pageData.items, function(i, r) { return t = r, i.orderId === n.menuChangedData.id || i.id === n.menuChangedData.id });
                            i && n.showInOrderDetail(i, t) } } else n.pageData.items[0] ? n.showInOrderDetail(n.pageData.items[0], 0) : (n.order = "", n.switchState(1));
                    n.initTableView() }) }) },
        v = function() { var t = o.getDefaultTimeSpan();
            t.startTime = moment(t.startTime).format("YYYY-MM-DD");
            t.endTime = moment(t.endTime).format("YYYY-MM-DD");
            n.searchCriteria = n.searchCriteria || { inOrderAction: "all", deliverType: "all", deliver: "请选择" };
            n.searchDateRange = n.state === 0 ? { startDate: "", endDate: "" } : { startDate: n.searchDateRange.startDate || t.startTime, endDate: n.searchDateRange.endDate || t.endTime } },
        c = function(t) { n.menuChangedData = t;
            n.state = t.state;
            n.triggerIndex = null;
            a() },
        y = function() { u.subscribe(n, u.events.IventoryInOrderCreated, function(t, i) { n.menuChangedData = i;
                c(i) });
            u.subscribe(n, u.events.IventoryActionMenuChanged, function(t, i) { n.menuChangedData = i;
                c(i) });
            u.subscribe(n, u.events.GlobalWarehouseChanged, function() { n.onSearchInOrderList() });
            u.subscribe(n, u.events.IventoryOrderDetailRendered, function() { n.initTableView() }) },
        p = function() { var t = s.showInOrderDetail;
            t && (n.menuChangedData = t, c(n.menuChangedData)) };
    (function() { n.isGroup = e.isGroup;
        n.searchInOrderList = l;
        n.initDefaultData = a;
        n.initSearchData = v;
        n.positioningTab = c;
        y();
        n.checkShowCertainInOrder = p })() }]);
supplychainModule.directive("inventoryInOrderListDetailEmptyView", [function() { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/inventory/inventory-in-order-list/components/inventory-in-order-list-detail-empty-view.html", link: function() {
            (function() {})() } } }]);
supplychainModule.directive("inventoryInOrderListDetailNoRefView", ["aresModalShelf", "aresConfirmDialog", "inventorySvc", "eventAggregator", "aresNotification", "inventoryUtil", function(n) { "use strict"; return { restrict: "E", replace: !0, scope: { order: "=", state: "=" }, controller: "InventoryInOrderListDetailCtrl", templateUrl: "/app/supplychain/views/inventory/inventory-in-order-list/components/inventory-in-order-list-detail-no-ref-view.html", link: function(t) { var i = function(i) { var r = n.open({ title: "编辑入库单", titleIconClass: "iconfont icon-ruku1", template: "<inventory-in-order-edit-modal-view><\/inventory-in-order-edit-modal-view>", controller: "InventoryInOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { inOrderId: i.id } } } });
                    r.result.then(function() { t.$parent.onSearchInOrderList ? t.$parent.onSearchInOrderList() : t.$parent.close() }) },
                r = function() { var i = n.open({ title: "新建入库单", titleIconClass: "iconfont icon-ruku1", template: "<inventory-in-order-edit-modal-view><\/inventory-in-order-edit-modal-view>", controller: "InventoryInOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { inOrderId: t.currentInventoryInOrder.id, action: "copyFromCancelled" } } } });
                    i.result.then(function(n) { t.menuChangedData = n;
                        t.$parent.positioningTab ? t.$parent.positioningTab(n) : t.$parent.close() }) },
                u = function() { var i = n.open({ title: "新建入库单", titleIconClass: "iconfont icon-ruku1", template: "<inventory-in-order-edit-modal-view><\/inventory-in-order-edit-modal-view>", controller: "InventoryInOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { inOrderId: t.currentInventoryInOrder.id, action: "cancelAndCopy" } } } });
                    i.result.then(function(n) { t.menuChangedData = n;
                        t.$parent.positioningTab ? t.$parent.positioningTab(n) : t.$parent.close() }) };
            (function() { t.onEditInOrder = i;
                t.copyCanceledInOrder = r;
                t.onCancelAndCopy = u })() } } }]);
supplychainModule.directive("inventoryInOrderListDetailWithRefView", ["aresModalShelf", "aresConfirmDialog", "inventorySvc", "eventAggregator", "aresNotification", "inventoryUtil", "procurementSvc", "enums", "$modal", "inventoryInOrderUtil", function(n, t, i, r, u, f, e, o, s) { "use strict"; return { restrict: "E", replace: !0, scope: { order: "=", state: "=" }, controller: "InventoryInOrderListDetailCtrl", templateUrl: "/app/supplychain/views/inventory/inventory-in-order-list/components/inventory-in-order-list-detail-with-ref-view.html", link: function(i) { var r = function() { t.warn({ message: "该单据仍有待入库的物品没有处理完毕，您确定要提前关闭该待处理单据吗？该关闭操作无法恢复。", onConfirm: function() { e.closeProcurementPayOrder(i.currentInventoryInOrder.referenceOrderId).success(function() { u.success("关闭成功!");
                                i.$parent.onSearchInOrderList ? i.$parent.onSearchInOrderList() : i.$parent.close() }).error(function(n) { f.showInventoryErrorMessage(n, "关闭失败") }) }, onCancel: function() {} }) },
                o = function() { var t = n.open({ title: "入库金额设置", template: "<procurement-in-order-amount-settings-view><\/procurement-in-order-amount-settings-view>", controller: "ProcurementInOrderAmountSettingsCtrl", resolve: { host: function() { return { order: angular.copy(i.referencedPayOrder), source: "InventoryInOrderList" } } }, needActive: !0 });
                    t.result.then(function() { i.init(i.order) }) },
                h = function(n) { if (n.refOutItems) { var t = s.open({ animation: !0, backdrop: "static", template: "<inventory-in-order-batch-dialog-view><\/inventory-in-order-batch-dialog-view>", controller: "InventoryInOrderBatchDialogCtrl", windowClass: "ares-medium-modal-content inventory-out-order-batch-dialog-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { orderItem: angular.copy(n) } } } });
                        t.result.then(function(t) { t && (n.refOutItems = t.refOutItems, n.curCount = t.curCount) }) } };
            (function() { i.closePayOrder = r;
                i.showAmountSettingsModal = o;
                i.showBatchItemCheckDialog = h })() } } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt) { this.$modal = n;
            this.$q = t;
            this.$log = i;
            this.$state = r;
            this.$scope = u;
            this.$filter = f;
            this.$sce = e;
            this.enums = o;
            this.dataDicSvc = s;
            this.loginContext = h;
            this.inventoryInOrderUtil = c;
            this.inventorySvc = l;
            this.supplyChainPrintUtil = a;
            this.aresConfirmDialog = v;
            this.aresNotification = y;
            this.inventoryUtil = p;
            this.inventoryWaybillUtil = w;
            this.warehouseUtil = b;
            this.permissionProvider = k;
            this.procurementSvc = d;
            this.eventAggregator = g;
            this.aresModalShelf = nt; var ot = function(n) { u.uiState = { isCheckedAll: !1, isShowPrice: !1, isShowDetailPatient: !1, isShowDetailReturnOffice: !1, isShowDetailUnTake: !1, isShowDetailCheckbox: !1, isShowDetailDeliverStatus: !1, isInventoryCostVisible: h.isInventoryCostAllowed }; var t = n;
                    u.uiState.isShowPrice = t && t.inOrderAction !== o.InOrderAction.UnTakeIn && (!t.referenceOrderId || t.inOrderAction === o.InOrderAction.PurchaseIn && h.isProcurementPriceAllowed);
                    u.uiState.isShowDetailPatient = t && c.isPatientRequiredForInOrder(t) && t.relatedType === 0;
                    u.uiState.isShowDetailReturnOffice = t && t.inOrderAction === o.InOrderAction.UnSalesIn && t.relatedType === 1;
                    u.uiState.isShowDetailUnTake = t && t.inOrderAction === o.InOrderAction.UnTakeIn && t.deliver;
                    u.uiState.isShowDetailCheckbox = t && t.referenceOrderId && (t.inOrderAction === o.InOrderAction.PurchaseIn || t.inOrderAction === o.InOrderAction.UnSalesIn);
                    u.uiState.isShowDetailDeliverStatus = t && (t.inOrderAction === o.InOrderAction.PurchaseIn && t.hasGroupSalesOrder || t.inOrderAction === o.InOrderAction.PurchaseIn && !t.hasGroupSalesOrder && t.organizationType > 0 || t.inOrderAction === o.InOrderAction.UnSalesIn && t.hasGroupSalesOrder) },
                st = function(n) { if (n) { var t = n.orderNumber,
                            i = n.inOrderAction == o.InOrderAction.UnpackIn || n.inOrderAction == o.InOrderAction.PackIn || n.inOrderAction == o.InOrderAction.TransferIn || n.inOrderAction == o.InOrderAction.AdjustIn ? "该单据已关联其他单据，作废后相关单据也会被作废，是否确定作废？" : "确认要作废入库单【" + t + "】？";
                        v.warn({ message: i, onConfirm: function() { l.cancelInOrder(n.id).success(function() { y.success("作废成功!");
                                    Ares.sensors.track("InventoryOperation", { OrderNumber: t, OperationType: "入库", OperationSubType: Ares.sensors.getInOrderActionString(n.inOrderAction), OperationMode: "作废" }); var i = { id: n.id, state: 2 };
                                    u.$parent.positioningTab ? u.$parent.positioningTab(i) : u.$parent.close() }).error(function(n) { p.showInventoryErrorMessage(n, "作废失败") }) }, onCancel: function() {} }) } },
                ht = function(n) { var r = t.defer(),
                        f; return u.referencedPayOrder = null, f = { orderid: n.orderId, type: n.preInOrderType }, u.preInOrderType = n.preInOrderType, l.getInOrder(f).success(function(n) { et(n);
                        r.resolve(!0) }).error(function(n) { y.error("无法获取订单详情");
                        i.log(n);
                        r.reject() }), r.promise },
                ct = function(n) { if (c.setOrderProperties(n, u), n.referenceOrderId > 0 && !n.state && (u.waybillsArr = [], n = w.formatOrderByWaybillNumber(n, u.waybillsArr)), n.hasGroupSalesOrder && !n.warehouseId && u.basicData.warehouses) { var t = b.getDefaultWarehouse(u.basicData.warehouses);
                        t && (n.warehouseId = t.id) } n = p.setBatchesByProductId(n);
                    n = w.orderItemsSort(n);
                    n.state > 0 && n.products && n.products.length > 0 && _.each(n.products, function(t) { t.batches && _.some(t.batches, function(n) { return n.unicode }) && (t.isShowLabelPrint = !0, n.isShowLabelPrint = !0) }) },
                lt = function() { d.getPayOrderFullById(u.currentInventoryInOrder.referenceOrderId).success(function(n) { u.referencedPayOrder = n; var t = 0;
                        _.each(n.procurementOrders, function(n) { _.each(n.procurementOrderItems, function(n) { t += n.itemCouponAmount }) });
                        u.canSetCouponFreight = (n.orderCouponAmount || n.freight) && moment(n.recordCreatedTime).isAfter("2019-03-01") }) },
                at = function(n) { var r, e, l, s; if (n) { var i = vt(n),
                            h = "",
                            c = "",
                            t = [],
                            o = f("toInOrderActionString")(n.inOrderAction); if (o = o.indexOf("入库") > -1 ? o + "单" : o + "入库单", r = { columnSettings: [70, 90, 150, 60, 200, 60, 80, 100, 100, 100, 100, 200, 150], title: "入库单" + n.orderNumber, fileName: "入库单" + n.orderNumber, headerRow: { value: o, colSpan: 13 }, contentRow: [] }, n.inOrderAction != 2) { switch (n.inOrderAction) {
                                case 1:
                                    h = "供应商：";
                                    c = n.dealer; break;
                                case 5:
                                    h = "退货单位：";
                                    c = n.deliverTypeStr + " " + n.deliver; break;
                                case 6:
                                    h = "退货员：";
                                    c = n.deliver } r.contentRow.push({ row: [{ cellType: "headerCell", value: "机构名称：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.officeName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "入库仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.warehouseName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: h, colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: c, colSpan: 4, textAlign: "left" }] }) } else r.contentRow.push({ row: [{ cellType: "headerCell", value: "调拨类型：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.transferOrder.orderType == 1 ? "跨机构调拨" : "机构内调拨", colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "调出仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.transferOrder.fromWarehouseName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "发货人：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.transferOrder.transfererName, colSpan: 4, textAlign: "left" }] }), n.transferOrder.orderType == 1 && (t.push({ cellType: "headerCell", value: "发出单位：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.transferOrder.fromOfficeName, colSpan: 4, textAlign: "left" })), t.push({ cellType: "headerCell", value: "调入仓库：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.transferOrder.toWarehouseName, colSpan: 3, textAlign: "left" }), t.push({ cellType: "headerCell", value: "收货人：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.transferOrder.receiverName, colSpan: 3, textAlign: "left" }), n.transferOrder.orderType != 1 && (t.push({ cellType: "headerCell", value: "入库单号：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.orderNumber, colSpan: 4, textAlign: "left" })), r.contentRow.push({ row: t });
                        t = [];
                        (n.inOrderAction != 2 || n.transferOrder != null && n.transferOrder.orderType == 1) && (t.push({ cellType: "headerCell", value: "入库单号：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.orderNumber, colSpan: 3, textAlign: "left" }));
                        t.push({ cellType: "headerCell", value: "单据日期：", colSpan: 1, textAlign: "left" });
                        t.push({ cellType: "regularCell", value: n.orderDateStr, colSpan: 3, textAlign: "left" });
                        t.push({ cellType: "headerCell", value: "制单人：", colSpan: 1, textAlign: "left" });
                        t.push({ cellType: "regularCell", value: n.operatorName, colSpan: 4, textAlign: "left" });
                        n.transferOrder != null && n.transferOrder.orderType != 1 && (t.push({ cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.notes ? n.notes : "无", colSpan: 4, textAlign: "left" }));
                        r.contentRow.push({ row: t });
                        i.isPatientRequire && r.contentRow.push({ row: [{ cellType: "headerCell", value: n.relatedType == 0 ? "患者：" : "退货机构：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.relatedName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.notes || "无", colSpan: 8, textAlign: "left" }] });
                        i.isPatientRequire || n.transferOrder != null && (n.transferOrder == null || n.transferOrder.orderType != 1) || r.contentRow.push({ row: [{ cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.notes || "无", colSpan: 12, textAlign: "left" }] });
                        t = [];
                        e = 0;
                        t.push({ cellType: "headerCell", value: "序号" });
                        e += 1;
                        u.productCodeOptions.allowInsideCode && (t.push({ cellType: "headerCell", value: "内部编码" }), e += 1);
                        l = 1 + (u.productCodeOptions.allowInsideCode ? 0 : 1);
                        t.push({ cellType: "headerCell", value: "名称", colSpan: l }, { cellType: "headerCell", value: "品牌" }, { cellType: "headerCell", value: "规格" }, { cellType: "headerCell", value: "单位" }, { cellType: "headerCell", value: "数量" });
                        e += 4 + l;
                        i.isShowPrice && (t.push({ cellType: "headerCell", value: f("toInOrderActionStringForTitle")(n.inOrderAction) }, { cellType: "headerCell", value: "金额" }), e += 2);
                        i.isBatchNumberVisible && (t.push({ cellType: "headerCell", value: "批号" }), e += 1);
                        i.isExpireDateVisible && (t.push({ cellType: "headerCell", value: "有效期至" }), e += 1);
                        s = 0;
                        i.isUnicodeVisible && (s = 1 + (i.isShowPrice ? 0 : 2), t.push({ cellType: "headerCell", value: "唯一码", colSpan: s }), e += s);
                        t.push({ cellType: "headerCell", value: "备注", colSpan: 13 - e });
                        r.contentRow.push({ row: t });
                        _.each(n.items, function(n, o) { t = [];
                            t.push({ cellType: "centerCell", value: o + 1 });
                            u.productCodeOptions.allowInsideCode && t.push({ cellType: "regularCell", value: n.code });
                            t.push({ cellType: "regularCell", value: n.name, colSpan: l });
                            t.push({ cellType: "regularCell", value: n.producer });
                            t.push({ cellType: "regularCell", value: n.specification });
                            t.push({ cellType: "centerCell", value: n.unit });
                            t.push({ cellType: "numberCell", value: n.count });
                            i.isShowPrice && t.push({ cellType: "priceCell", value: n.price }, { cellType: "priceCell", value: n.amount });
                            i.isBatchNumberVisible && t.push({ cellType: "centerCell", value: n.batchNumber });
                            i.isExpireDateVisible && t.push({ cellType: "centerCell", value: f("toDateString")(n.expiredDate) });
                            i.isUnicodeVisible && t.push({ cellType: "centerCell", value: n.unicode, colSpan: s });
                            t.push({ cellType: "regularCell", value: n.notes, colSpan: 13 - e });
                            r.contentRow.push({ row: t }) });
                        t = [];
                        t.push({ cellType: "headerCell", value: "合计", colSpan: 6, textAlign: "left" });
                        t.push({ cellType: "numberCell", value: i.totalCount, colSpan: 1 });
                        i.isShowPrice && t.push({ cellType: "priceCell", value: "" }, { cellType: "priceCell", value: i.totalAmount });
                        t.push({ cellType: "regularCell", value: "", colSpan: 6 - (i.isShowPrice ? 2 : 0) });
                        r.contentRow.push({ row: t });
                        r.contentRow.push({ row: [{ cellType: "regularCell", value: "", colSpan: 8 }, { cellType: "headerCell", value: "经办人：" + (n.receiverId ? n.receiverStr : ""), colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "经办人签字：", colSpan: 2, textAlign: "left" }] });
                        p.exportExcel(r) } },
                vt = function(n) { var t = {},
                        e;
                    t.isPatientRequire = c.isPatientRequiredForInOrder(n);
                    n.officeId && (e = u.basicData.offices.find(function(t) { return t.id == n.officeId }), t.officeName = e.name); var o = 0,
                        s = 0,
                        i = !1,
                        r = !1,
                        f = !1; return n.items.forEach(function(t) {
                        (n.inOrderAction === 0 || n.inOrderAction === 6) && (t.price = t.businessAmount / t.count, t.amount = t.businessAmount);
                        o += t.count;
                        s += t.amount;
                        i = i || t.expiredDate;
                        r = r || t.batchNumber;
                        f = f || t.unicode }), t.totalCount = o, t.totalAmount = s, t.isExpireDateVisible = i, t.isBatchNumberVisible = r, t.isUnicodeVisible = f, t.isShowPrice = n.inOrderAction != 5 && (!n.referenceOrderId || n.referenceOrderId > 0 && n.inOrderAction == 1 && h.isProcurementPriceAllowed), t },
                yt = function(n, t) { var i = [],
                        r;
                    t ? i = [t] : n ? i = n.batches : _.each(u.currentInventoryInOrder.products, function(n) { n.batches && _.some(n.batches, function(n) { return n.unicode }) && (i = i.concat(n.batches)) });
                    r = _.map(i, function(n) { return { itemId: n.id, name: n.product.name, specification: n.product.specification, producer: n.product.producer, producerCompany: n.product.producerCo, batchNumber: n.batchNumber, expiredDate: n.expiredDate, count: n.count, unit: n.product.unit, unicode: n.unicode, printTime: moment().format("YYYY-MM-DD HH:mm:ss"), printPerson: h.userName } });
                    u.$broadcast("productLabels", r) },
                pt = function(n) { var t = angular.copy(n);
                    a.printInventoryInOrder(t, u) },
                wt = function(n, t) { var i = n.id;
                    g.publish(g.events.ProductSelected, i, t.delegateTarget) },
                bt = function(n) { var t = n.id;
                    c.viewOperationLog(t, "InventoryInOrder") },
                kt = function() { ut(); var n = u.currentInventoryInOrder;
                    n.products.forEach(function(n) { n.unInStorageNum > 0 && (n.isChecked = u.uiState.isCheckedAll) });
                    n.items.forEach(function(n) { n.isChecked = u.uiState.isCheckedAll });
                    tt(n) },
                dt = function(n) { ut(); var t = u.currentInventoryInOrder;
                    _.each(t.items, function(t) { t.productId == n.id && (t.isChecked = n.isChecked) });
                    u.uiState.isCheckedAll = _.every(t.items, function(n) { return n.isChecked || n.unInStorageNum === 0 });
                    tt(t) },
                tt = function(n) { var t = _.filter(n.products, function(n) { return n.isChecked && n.unInStorageNum > 0 });
                    n.selectedProductsNum = t.length;
                    u.uiState.isCheckedAll = _.every(n.products, function(n) { return n.isChecked || n.unInStorageNum === 0 }) },
                gt = function(t) { n.open({ animation: !0, backdrop: "static", template: "<inventory-in-order-count-view><\/inventory-out-order-count-view>", controller: "InventoryInOrderCountCtrl", windowClass: "ares-medium-modal-content product-batch inventory-in-order-count-model-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { orderItem: angular.copy(t), isInventoryCostVisible: u.uiState.isInventoryCostVisible, printProductLabel: u.printProductLabel } } } }) },
                ni = function(n) { n.isSelected = !n.isSelected;
                    ti() },
                ti = function() { var n = [];
                    _.each(u.waybillsArr, function(t) { t.isSelected && (n = n.concat(t.items)) });
                    n.length > 0 ? (u.currentInventoryInOrder.items = n, _.each(u.currentInventoryInOrder.items, function(n) { ii(n) }), ri(u.currentInventoryInOrder)) : (u.currentInventoryInOrder.items = angular.copy(u.currentInventoryInOrderCache.items), rt(u.currentInventoryInOrder));
                    tt(u.currentInventoryInOrder) },
                ii = function(n) {
                    (n.deliveredStatus === o.ProcurementOrderItemDeliveredStatus.Pending || n.deliveredStatus === o.ProcurementOrderItemDeliveredStatus.Delivered || n.deliveredStatus === o.ProcurementOrderItemDeliveredStatus.PartDelivered) && (n.isChecked = !0) },
                ri = function(n) { rt(n);
                    _.each(n.products, function(t) { var i = _.find(n.items, function(n) { return n.productId == t.id });
                        i && i.unInStorageNum > 0 && (t.isChecked = i.isChecked) });
                    n = p.orderProductsSortByIsChecked(n) },
                rt = function(n) { _.each(n.products, function(n) { n.isChecked = !1 }) },
                ut = function() { _.each(u.waybillsArr, function(n) { n.isSelected = !1 });
                    u.currentInventoryInOrder.items = angular.copy(u.currentInventoryInOrderCache.items);
                    _.each(u.currentInventoryInOrder.items, function(n) { var t = _.find(u.currentInventoryInOrder.products, function(t) { return n.productId == t.id });
                        t && t.unInStorageNum > 0 && (n.isChecked = t.isChecked) }) },
                ft = function() { var n = u.currentInventoryInOrder;
                    v.warn({ message: "您确定执行该单据吗？单据执行后库存将发生变更", onConfirm: function() { l.approveInOrder(n.id).success(function() { g.publish(g.events.RefreshIventoryHint, null, "InventoryInOrderListDetailCtrl");
                                y.success("入库成功!");
                                Ares.sensors.track("InventoryOperation", { OrderNumber: n.orderNumber, OperationType: "入库", OperationSubType: Ares.sensors.getInOrderActionString(n.inOrderAction), OperationMode: "执行入库" });
                                u.$parent.onSearchInOrderList ? u.$parent.onSearchInOrderList() : u.$parent.close() }).error(function(n) { p.showInventoryErrorMessage(n, "入库失败") }) }, onCancel: function() {} }) },
                ui = function() { var n = angular.copy(u.currentInventoryInOrder),
                        t, r, i; if (!n.warehouseId) { y.error("选择入库仓库！"); return } if (t = _.filter(n.products, function(n) { return n.isChecked && n.refOutItems != null && n.refOutItems.length > 0 }), r = _.any(t, function(n) { return !_.any(n.refOutItems, function(n) { return n.curCount > 0 }) }), r) { y.error("选择入库的物品未确认入库批次信息！"); return } i = [];
                    _.each(t, function(n) { _.each(n.refOutItems, function(n) { if (n.curCount > 0) { var t = { productId: n.productId, batchNumber: n.batchNumber, expiredDate: n.expiredDate, unicode: n.unicode, count: n.curCount };
                                i.push(t) } }) });
                    n.items = i;
                    v.warn({ message: "您确定入库选择的物品吗？执行后库存将发生变更", onConfirm: function() { l.saveAndApproveInOrder(n).success(function() { g.publish(g.events.RefreshIventoryHint, null, "InventoryInOrderListDetailCtrl");
                                y.success("入库成功!");
                                u.$parent.onSearchInOrderList ? u.$parent.onSearchInOrderList() : u.$parent.close() }).error(function(n) { p.showInventoryErrorMessage(n, "入库失败") }) }, onCancel: function() {} }) },
                fi = function() { var n, t, i, f, e; if (u.currentInventoryInOrder.inOrderAction === o.InOrderAction.TransferIn) { ft(); return } if (n = _.filter(u.currentInventoryInOrder.items, function(n) { return n.isChecked && n.unInStorageNum !== 0 }), !n.length) { y.error("请选择需要入库的物品！"); return } if (u.currentInventoryInOrder.hasGroupSalesOrder && u.currentInventoryInOrder.inOrderAction == 1) { if (t = _.filter(u.currentInventoryInOrder.items, function(n) { return n.refOutItems != null && n.refOutItems.length > 0 }), t && t.length > 0) { ui(); return } y.error("当前采购单总部还未出库！"); return } i = p.setOrderItemsByProductId(u.currentInventoryInOrder, n, u.currentInventoryInOrder.preInOrderType);
                    f = _.pluck(_.filter(u.waybillsArr, function(n) { return n.isSelected }), "waybillNum");
                    _.each(i.items, function(n) { n.batches = [angular.copy(n)];
                        delete n.products;
                        f.length > 0 && (n.waybillInfos = _.filter(n.waybillInfos, function(n) { return f.indexOf(n.waybillInfo) > -1 })) });
                    e = nt.open({ title: "新建入库单", titleIconClass: "iconfont icon-ruku1", template: "<inventory-in-order-edit-modal-view><\/inventory-in-order-edit-modal-view>", controller: "InventoryInOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { inOrder: i } } } });
                    e.result.then(function() { u.$parent.onSearchInOrderList ? r.go(".", { showInOrderDetail: null }).then(function() { u.$parent.onSearchInOrderList() }) : u.$parent.close() }) },
                ei = function(n) { var t = this.dataItem(n.item.index());
                    t && t.id == -1 && (n.preventDefault(), y.error("寄售仓库不支持当前操作！")) },
                et = function(n) { ct(n);
                    u.currentInventoryInOrder = n;
                    u.currentInventoryInOrderCache = angular.copy(n); var t = u.currentInventoryInOrder.inOrderAction === 1 && u.currentInventoryInOrder.referenceOrderId > 0 && _.every(u.currentInventoryInOrder.items, function(n) { return n.inStorageNum === 0 });
                    t ? lt() : u.canSetCouponFreight = !1;
                    ot(u.currentInventoryInOrder) },
                it = function(n) { u.state === 0 ? ht(n).then(function() { g.publish(g.events.IventoryOrderDetailRendered, null, "InventoryInOrderListDetailCtrl") }) : (et(n), g.publish(g.events.IventoryOrderDetailRendered, null, "InventoryInOrderListDetailCtrl")) };
            (function() { u.preInOrderType = 0;
                u.isGroup = h.isGroup;
                u.onCancelInOrder = st;
                u.exportExcel = at;
                u.isProcurementPriceAllowed = h.isProcurementPriceAllowed;
                u.printProductLabel = yt;
                u.onSelectProduct = wt;
                u.printInOrder = pt;
                u.viewOperationLog = bt;
                u.setWaybillOrderCheck = kt;
                u.checkOrderIsChecked = dt;
                u.showBatchItemDialog = gt;
                u.calculateCheckedProductsNum = tt;
                u.waybillChange = ni;
                u.processInOrderNoRef = ft;
                u.processInOrderWithRef = fi;
                u.onWarehouseSelected = ei;
                u.init = it;
                c.initBaseData(u).then(function() { it(u.order) });
                u.$watch("order", function(n) { it(n) }) })() } return n.$inject = ["$modal", "$q", "$log", "$state", "$scope", "$filter", "$sce", "enums", "dataDicSvc", "loginContext", "inventoryInOrderUtil", "inventorySvc", "supplyChainPrintUtil", "aresConfirmDialog", "aresNotification", "inventoryUtil", "inventoryWaybillUtil", "warehouseUtil", "permissionProvider", "procurementSvc", "eventAggregator", "aresModalShelf"], n }();
    supplychainModule.controller("InventoryInOrderListDetailCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryOutOrderListView", ["$q", "$timeout", "$window", "enums", "inventoryOutOrderUtil", function(n, t, i, r, u) { return { replace: !0, templateUrl: "/app/supplychain/views/inventory/inventory-out-order-list/inventory-out-order-list-view.html", controller: "InventoryOutOrderListCtrl", link: function(f, e) { var h = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } },
                l = function() { o(); var n = angular.element(i);
                    n.on("resize", function() { o() }) },
                o = function() { var r = angular.element(i).height(),
                        u = 110,
                        o, n;
                    f.uiState.isShowAdvancedSearch && (u = 374, f.state || (u -= 44)); var s = r - u - 145 - (window.Ares3 ? 10 : 0),
                        t = e.find(".left-side-container .table-main .table-main-content");
                    t.height(s);
                    t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar(h); var c = r - 130 - (window.Ares3 ? 10 : 0),
                        l = e.find(".right-side-container .detail-list");
                    l.height(c);
                    o = r - 300;
                    n = e.find(".right-side-container .table-main .table-main-content:visible");
                    n.height(o);
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(h) },
                s = function(i) { var r = n.defer(); return f.page.pageIndex = i ? f.page.pageIndex : 1, f.searchOutOrderList().then(function() { t(function() { f.pageData.items[0] ? c(f.pageData.items[0], 0) : f.order = "";
                            o();
                            r.resolve() }) }), r.promise },
                a = function(n) { var t = window.event ? n.keyCode : n.which;
                    t === 13 && s() },
                c = function(n, t) { f.triggerIndex = t;
                    f.order = n },
                v = function(n) { f.state !== n && (f.state = n, f.outOrderActionOptions = n === 0 ? f.basicData.outOrderActionSearchTypes.pending : f.basicData.outOrderActionSearchTypes.other, f.initSearchData(), _.some(f.outOrderActionOptions, function(n) { return n.value == f.searchCriteria.outOrderAction }) || (f.searchCriteria.outOrderAction = "all"), f.order = null, s()) },
                y = function() { f.uiState.isShowAdvancedSearch = !f.uiState.isShowAdvancedSearch;
                    o() },
                p = function() { f.searchCriteria.consigneeType == r.InOrderDeliverType.Provider && (f.consigneeDataSource = f.basicData.staffs, f.searchCriteria.consignee = "全部员工");
                    f.searchCriteria.consigneeType == r.InOrderDeliverType.Operatory && (f.consigneeDataSource = f.basicData.operatories, f.searchCriteria.consignee = "全部诊室");
                    f.searchCriteria.consigneeType == r.InOrderDeliverType.Department && (f.consigneeDataSource = f.basicData.departments, f.searchCriteria.consignee = "全部科室");
                    f.searchCriteria.consigneeType === "all" && (f.consigneeDataSource = [{ name: "请选择" }], f.searchCriteria.consignee = "请选择");
                    f.onSearchOutOrderList() },
                w = function(n) { f.searchDateRange.startDate = n.startDate;
                    f.searchDateRange.endDate = n.endDate;
                    f.onSearchOutOrderList() };
            (function() { f.uiState = { consigneeType: { onChange: p }, isShowAdvancedSearch: !1 };
                f.state = 0;
                f.page = { pageIndex: 1, pageSize: 20 };
                f.kendoDatePickerOptions = { format: "yyyy-MM-dd", max: new Date };
                f.isAres3 = window.Ares3;
                f.onSearchOutOrderList = s;
                f.onEnter = a;
                f.initTableView = o;
                f.outOrderDetail = c;
                f.switchState = v;
                f.toggleAdvancedSearch = y;
                f.onDateRangeChanged = w;
                l();
                u.initBasicData(f).then(function() { f.checkShowCertainOutOrder();
                    f.initDefaultData() }) })() } } }]);
supplychainModule.controller("InventoryOutOrderListCtrl", ["$log", "$q", "$rootScope", "$timeout", "eventAggregator", "$scope", "inventorySvc", "loginContext", "reportUtil", "$stateParams", "inventoryOutOrderUtil", function(n, t, i, r, u, f, e, o, s, h, c) { "use strict"; var a = function() { var n = angular.copy(f.searchCriteria),
                r, u; return n.pageIndex = f.page.pageIndex, n.pageSize = f.page.pageSize, r = f.state, n.state === "all" && (n.state = null), n.dealer = n.dealer === "所属供应商" ? null : n.dealer, n.operatorId && n.operatorId !== "0" || (n.operatorId = null), n.senderId && n.senderId !== "0" || (n.senderId = null), n.consigneeType === "all" && (n.consigneeType = null), (n.consignee === "all" || n.consignee === "请选择" || n.consignee === "全部员工" || n.consignee === "全部科室" || n.consignee === "全部诊室") && (n.consignee = null), n.outOrderAction === "all" && (n.outOrderAction = null), n.relatedOffice === "-1" && (n.relatedOffice = null), n.startDate = f.searchDateRange.startDate ? moment(f.searchDateRange.startDate).format("YYYY-MM-DD") : null, n.endDate = f.searchDateRange.endDate ? moment(f.searchDateRange.endDate).add(1, "days").format("YYYY-MM-DD") : null, n.warehouseId = i.currentWarehouseId != 0 ? i.currentWarehouseId : null, u = t.defer(), r ? (n.waybillNo = "", n.state = r) : (n.createdUserId = n.operatorId, n.operatorId = n.senderId, n.orderAction = n.outOrderAction), e.searchOutOrder(n, r).success(function(n) { f.pageData = n.page ? n.page : n;
                f.page.totalCount = f.pageData.totalCount;
                f.page.pageCount = f.pageData.pageCount || 1;
                b(f.pageData.items);
                u.resolve() }), u.promise },
        v = function() { y();
            a().then(function() { r(function() { var n, t, i;
                    f.menuChangedData ? f.menuChangedData && f.menuChangedData.id && (t = 0, i = _.find(f.pageData.items, function(n, i) { return t = i, n.orderId === f.menuChangedData.id || n.id === f.menuChangedData.id }), i && f.outOrderDetail(i, t)) : (n = f.pageData.items[0], n ? f.outOrderDetail(n, 0) : (f.order = "", f.switchState(1)));
                    f.initTableView() }) }) },
        y = function() { var n = s.getDefaultTimeSpan();
            n.startTime = moment(n.startTime).format("YYYY-MM-DD");
            n.endTime = moment(n.endTime).format("YYYY-MM-DD");
            f.searchCriteria = f.searchCriteria || { outOrderAction: "all", state: "all", consigneeType: "all", consignee: "请选择", senderId: "0", dealer: "所属供应商", operatorId: "0", relatedOffice: "-1" };
            f.state === 0 ? f.searchDateRange = { startDate: "", endDate: "" } : (f.searchDateRange = f.searchDateRange || {}, f.searchDateRange = { startDate: f.searchDateRange.startDate || n.startTime, endDate: f.searchDateRange.endDate || n.endTime }) },
        l = function(n) { f.menuChangedData = n;
            f.state = n.state;
            f.triggerIndex = null;
            v() },
        p = function() { u.subscribe(f, u.events.IventoryOutOrderCreated, function(n, t) { f.menuChangedData = t;
                l(t) });
            u.subscribe(f, u.events.IventoryActionMenuChanged, function(n, t) { f.menuChangedData = t;
                l(t) });
            u.subscribe(f, u.events.GlobalWarehouseChanged, function() { f.onSearchOutOrderList() });
            u.subscribe(f, u.events.IventoryOrderDetailRendered, function() { f.initTableView() }) },
        w = function() { var n = h.showOutOrderDetail;
            n && (f.menuChangedData = n, l(f.menuChangedData)) },
        b = function(n) { angular.forEach(n, function(n) { n && c.formatOrderUnit(n, f) }) };
    (function() { f.isGroup = o.isGroup;
        f.searchOutOrderList = a;
        f.initDefaultData = v;
        f.positioningTab = l;
        f.checkShowCertainOutOrder = w;
        f.initSearchData = y;
        p() })() }]);
supplychainModule.directive("inventoryOutOrderListDetailNoRefView", [function() { "use strict"; return { restrict: "E", replace: !0, scope: { order: "=", state: "=" }, controller: "InventoryOutOrderListDetailCtrl", templateUrl: "/app/supplychain/views/inventory/inventory-out-order-list/components/inventory-out-order-list-detail-no-ref-view.html", link: function() {
            (function() {})() } } }]);
supplychainModule.directive("inventoryOutOrderListDetailWithRefDoneView", [function() { "use strict"; return { restrict: "E", replace: !0, scope: { order: "=", state: "=" }, controller: "InventoryOutOrderListDetailCtrl", templateUrl: "/app/supplychain/views/inventory/inventory-out-order-list/components/inventory-out-order-list-detail-with-ref-done-view.html", link: function() {
            (function() {})() } } }]);
supplychainModule.directive("inventoryOutOrderListDetailWithRefPendingView", [function() { "use strict"; return { restrict: "E", replace: !0, scope: { order: "=", state: "=" }, controller: "InventoryOutOrderListDetailCtrl", templateUrl: "/app/supplychain/views/inventory/inventory-out-order-list/components/inventory-out-order-list-detail-with-ref-pending-view.html", link: function() {
            (function() {})() } } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) { var tt = function(n) { if (n) { var t = n.orderNumber,
                            u = n.outOrderAction == r.OutOrderAction.AdjustOut || n.outOrderAction == r.OutOrderAction.PackOut || n.outOrderAction == r.OutOrderAction.UnpackOut || n.outOrderAction == r.OutOrderAction.TransferOut ? "该单据已关联其他单据，作废后相关单据也会被作废，是否确定作废?" : "确认要作废出库单【" + t + "】?";
                        h.confirm({ message: u }).then(function() { a.cancelOutOrder(n.id).success(function() { l.success("作废成功!");
                                Ares.sensors.track("InventoryOperation", { OrderNumber: t, OperationType: "出库", OperationSubType: Ares.sensors.getOutOrderActionString(n.outOrderAction), OperationMode: "作废" });
                                i.menuChangedData = { id: n.id, state: 2 };
                                i.$parent.positioningTab ? i.$parent.positioningTab(i.menuChangedData) : i.$parent.close() }).error(function(n) { var t = n.message || "作废失败";
                                y.showInventoryErrorMessage(n, t) }) }) } },
                it = function(n) { i.onCopyOutOrder(n.id).then(function(n) { i.menuChangedData = n;
                        i.$parent.positioningTab ? i.$parent.positioningTab(i.menuChangedData) : i.$parent.close() }) },
                rt = function(n) { if (n.referenceOrderId && (n.outOrderAction == r.OutOrderAction.TakeOut || n.outOrderAction == r.OutOrderAction.SalesOut || n.outOrderAction == r.OutOrderAction.ProcurementReturnOut)) i.onEditOutOrder(n);
                    else(!n.referenceOrderId || n.referenceOrderId && n.outOrderAction == r.OutOrderAction.TransferOut) && h.warn({ message: "您确定执行该单据吗？单据执行后库存将发生变更", onConfirm: function() { a.approveOutOrder(n.id).success(function() { o.publish(o.events.RefreshIventoryHint, null, "InventoryOutOrderListDetailCtrl");
                                l.success("出库成功!");
                                Ares.sensors.track("InventoryOperation", { OrderNumber: n.orderNumber, OperationType: "出库", OperationSubType: Ares.sensors.getOutOrderActionString(n.outOrderAction), OperationMode: "执行出库" });
                                i.$parent.onSearchOutOrderList ? i.$parent.onSearchOutOrderList() : i.$parent.close() }).error(function(n) { y.showInventoryErrorMessage(n, "出库失败") }) }, onCancel: function() {} }) },
                ut = function(n) { h.warn({ message: "该单据仍有待出库的物品没有处理完毕，您确定要提前关闭该待处理单据吗？该关闭操作无法恢复。", onConfirm: function() { a.closeTakeOrder(n.referenceOrderId).success(function() { l.success("关闭成功!");
                                i.$parent.onSearchOutOrderList ? i.$parent.onSearchOutOrderList() : i.$parent.close() }).error(function(n) { y.showInventoryErrorMessage(n, "关闭失败") }) }, onCancel: function() {} }) },
                ft = function(n) { var u = n.products,
                        t = _.sortBy(u, function(n) { return n.id }),
                        r = _.filter(t, function(n) { return n.inventoryCount === 0 }),
                        f = _.difference(t, r);
                    n.products = f.concat(r);
                    n.referenceOrderId > 0 && (i.uiState.isCheckedAll = !0, i.setOrderCheck()) },
                b = function(n) { u.formatOrderUnit(n, i);
                    et(n) },
                et = function(n) { var t = [],
                        i = _.groupBy(n.items, "productId"),
                        u = _.keys(i);
                    n.hasBusinessAmount = 0;
                    n.businessAmount = 0;
                    n.referenceOrderId || n.outOrderAction != r.OutOrderAction.SalesOut && n.outOrderAction != r.OutOrderAction.ProcurementReturnOut || (n.hasBusinessAmount = 1);
                    angular.forEach(u, function(r) { var f = i[r],
                            u = { id: r, name: f[0].name, producer: f[0].producer, specification: f[0].specification, code: f[0].code, unit: f[0].unit, outCount: 0, inventoryCount: 0, hasOutStorageNum: 0, unOutStorageNum: 0, price: 0, amount: 0, businessAmount: 0, businessPrice: 0, notes: f[0].notes, batches: f, isShowBatch: 0, state: n.state, outOrderAction: n.outOrderAction },
                            e;
                        angular.forEach(f, function(n) { u.outCount += n.count;
                            u.inventoryCount += n.batchTotalCount;
                            u.unOutStorageNum += n.unOutStorageNum;
                            u.hasOutStorageNum += n.count - n.unOutStorageNum;
                            u.price += n.price;
                            u.businessAmount += n.businessAmount;
                            u.amount += n.amount;
                            (n.expiredDate || n.batchNumber) && (u.isShowBatch = 1) });
                        e = Ares.priceToFixed(u.amount / u.outCount);
                        u.businessPrice = Ares.priceToFixed(u.businessAmount / u.outCount);
                        u.price = u.price > e ? e : u.price;
                        t.push(u);
                        n.businessAmount += u.businessAmount });
                    n.products = t },
                ot = function() { return u.isPatientRequiredForOutOrder(i.currentInventoryOutOrder) },
                st = function(n) { var u, h, e; if (n) { var r = ht(n),
                            o = "",
                            s = "",
                            t = [],
                            f = { columnSettings: [70, 70, 150, 60, 200, 60, 80, 80, 100, 100, 100, 100, 100, 200, 150], title: "出库单" + n.orderNumber, fileName: "出库单" + n.orderNumber, headerRow: { value: p("toOutOrderActionString")(n.outOrderAction) + "单", colSpan: 15 }, contentRow: [] }; if (n.outOrderAction != 2) { switch (n.outOrderAction) {
                                case 1:
                                    o = "收货单位：";
                                    s = n.consigneeTypeStr + " " + n.consignee; break;
                                case 5:
                                    o = "销售员：";
                                    s = n.consignee; break;
                                case 6:
                                    o = "供应商：";
                                    s = n.consignee } f.contentRow.push({ row: [{ cellType: "headerCell", value: "机构名称：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: r.officeName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "出库仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.warehouseName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: o, colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: s, colSpan: 6, textAlign: "left" }] }) } else f.contentRow.push({ row: [{ cellType: "headerCell", value: "调拨类型：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.transferOrder.orderType == 1 ? "跨机构调拨" : "机构内调拨", colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "调出仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.transferOrder.fromWarehouseName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "发货人：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.transferOrder.transfererName, colSpan: 6, textAlign: "left" }] }), n.transferOrder.orderType == 1 && (t.push({ cellType: "headerCell", value: "收入单位：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.transferOrder.toOfficeName, colSpan: 3, textAlign: "left" })), t.push({ cellType: "headerCell", value: "调入仓库：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.transferOrder.toWarehouseName, colSpan: 3, textAlign: "left" }), t.push({ cellType: "headerCell", value: "收货人：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.transferOrder.receiverName, colSpan: n.transferOrder.orderType == 1 ? 6 : 3, textAlign: "left" }), n.transferOrder.orderType != 1 && (t.push({ cellType: "headerCell", value: "出库单号：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.orderNumber, colSpan: 6, textAlign: "left" })), f.contentRow.push({ row: t });
                        t = [];
                        (n.outOrderAction != 2 || n.transferOrder.orderType == 1) && (t.push({ cellType: "headerCell", value: "出库单号：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.orderNumber, colSpan: 3, textAlign: "left" }));
                        t.push({ cellType: "headerCell", value: "单据日期：", colSpan: 1, textAlign: "left" });
                        t.push({ cellType: "regularCell", value: n.orderDateStr, colSpan: 3, textAlign: "left" });
                        t.push({ cellType: "headerCell", value: "制单人：", colSpan: 1, textAlign: "left" });
                        t.push({ cellType: "regularCell", value: n.operatorName, colSpan: n.outOrderAction != 2 || n.transferOrder.orderType == 1 ? 6 : 3, textAlign: "left" });
                        n.transferOrder != null && n.transferOrder.orderType != 1 && (t.push({ cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }), t.push({ cellType: "regularCell", value: n.notes || "无", colSpan: 6, textAlign: "left" }));
                        f.contentRow.push({ row: t });
                        r.isPatientRequire && f.contentRow.push({ row: [{ cellType: "headerCell", value: n.relatedType == 0 ? "患者：" : "收货机构：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.relatedName, colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.notes || "无", colSpan: 10, textAlign: "left" }] });
                        r.isPatientRequire || n.transferOrder != null && (n.transferOrder == null || n.transferOrder.orderType != 1) || f.contentRow.push({ row: [{ cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: n.notes || "无", colSpan: 14, textAlign: "left" }] });
                        t = [];
                        u = 0;
                        t.push({ cellType: "headerCell", value: "序号" });
                        u += 1;
                        i.productCodeOptions.allowInsideCode && (t.push({ cellType: "headerCell", value: "内部编码" }), u += 1);
                        h = 1 + (i.productCodeOptions.allowInsideCode ? 0 : 1);
                        t.push({ cellType: "headerCell", value: "名称", colSpan: h }, { cellType: "headerCell", value: "品牌" }, { cellType: "headerCell", value: "规格" }, { cellType: "headerCell", value: "单位" }, { cellType: "headerCell", value: "数量" });
                        u += 4 + h;
                        r.isShowCostPrice && (t.push({ cellType: "headerCell", value: "成本单价" }), u += 1);
                        r.isShowPrice && (t.push({ cellType: "headerCell", value: p("toOutOrderActionStringForTitle")(n.outOrderAction) }), u += 1);
                        r.isShowCostPrice && (t.push({ cellType: "headerCell", value: "成本总额" }), u += 1);
                        r.isShowPrice && (t.push({ cellType: "headerCell", value: "金额" }), u += 1);
                        r.isBatchNumberVisible && (t.push({ cellType: "headerCell", value: "批号" }), u += 1);
                        r.isExpireDateVisible && (t.push({ cellType: "headerCell", value: "有效期至" }), u += 1);
                        e = 0;
                        r.isUnicodeVisible && (e = 1 + (r.isShowPrice ? 0 : 2), t.push({ cellType: "headerCell", value: "唯一码", colSpan: e }), u += e);
                        t.push({ cellType: "headerCell", value: "备注", colSpan: 15 - u });
                        f.contentRow.push({ row: t });
                        _.each(n.items, function(n, o) { n.count != 0 && (t = [], t.push({ cellType: "centerCell", value: o + 1 }), i.productCodeOptions.allowInsideCode && t.push({ cellType: "centerCell", value: n.code }), t.push({ cellType: "regularCell", value: n.name, colSpan: h }), t.push({ cellType: "regularCell", value: n.producer }), t.push({ cellType: "regularCell", value: n.specification }), t.push({ cellType: "centerCell", value: n.unit }), t.push({ cellType: "numberCell", value: n.count }), r.isShowCostPrice && t.push({ cellType: "priceCell", value: n.price }), r.isShowPrice && n.count && t.push({ cellType: "priceCell", value: n.businessAmount / n.count }), r.isShowCostPrice && t.push({ cellType: "priceCell", value: n.amount }), r.isShowPrice && t.push({ cellType: "priceCell", value: n.businessAmount }), r.isBatchNumberVisible && t.push({ cellType: "centerCell", value: n.batchNumber }), r.isExpireDateVisible && t.push({ cellType: "centerCell", value: p("toDateString")(n.expiredDate) }), r.isUnicodeVisible && t.push({ cellType: "centerCell", value: n.unicode, colSpan: e }), t.push({ cellType: "regularCell", value: n.notes, colSpan: 15 - u }), f.contentRow.push({ row: t })) });
                        t = [];
                        t.push({ cellType: "headerCell", value: "合计", colSpan: 6, textAlign: "left" });
                        t.push({ cellType: "numberCell", value: r.totalCount, colSpan: 1 });
                        r.isShowCostPrice && t.push({ cellType: "priceCell", value: "" });
                        r.isShowPrice && t.push({ cellType: "priceCell", value: "" });
                        r.isShowCostPrice && t.push({ cellType: "priceCell", value: r.totalAmount });
                        r.isShowPrice && t.push({ cellType: "priceCell", value: r.totalBussinessAmount });
                        t.push({ cellType: "regularCell", value: "", colSpan: 8 - (r.isShowCostPrice ? 2 : 0) - (r.isShowPrice ? 2 : 0) });
                        f.contentRow.push({ row: t });
                        f.contentRow.push({ row: [{ cellType: "regularCell", value: "", colSpan: 5 }, { cellType: "headerCell", value: "经办人：" + (n.senderId ? n.senderName : ""), colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "经办人签字：", colSpan: 3, textAlign: "left" }, { cellType: "headerCell", value: "收货单位签字：", colSpan: 4, textAlign: "left" }] });
                        y.exportExcel(f) } },
                ht = function(n) { var t = {},
                        o;
                    t.isPatientRequire = u.isPatientRequiredForOutOrder(n);
                    n.officeId && (o = i.basicData.offices.find(function(t) { return t.id == n.officeId }), t.officeName = o.name); var s = 0,
                        h = 0,
                        c = 0,
                        r = !1,
                        f = !1,
                        e = !1; return n.items.forEach(function(n) { s += n.count;
                        c += n.businessAmount;
                        h += n.amount;
                        r = r || n.expiredDate;
                        f = f || n.batchNumber;
                        e = e || n.unicode }), t.totalCount = s, t.totalAmount = h, t.totalBussinessAmount = c, t.isExpireDateVisible = r, t.isBatchNumberVisible = f, t.isUnicodeVisible = e, t.isShowCostPrice = v.isInventoryCostAllowed && n.state == 1, t.isShowPrice = (n.outOrderAction == 5 || n.outOrderAction == 6) && !n.referenceOrderId, t.recordCreatedTimeStr = moment(n.recordCreatedTime).format("YYYY-MM-DD HH:mm:ss"), t },
                ct = function(n) { var t = n.sender.value(),
                        r;
                    i.currentInventoryOutOrder.warehouseId = t;
                    i.currentInventoryOutOrder.outWarehouseId = t;
                    t == -1 && (i.basicData.dealerWarehouses && i.basicData.dealerWarehouses.length > 0 ? i.currentInventoryOutOrder.consignmentDealerId ? (r = _.find(i.baseData.dealerWarehouses, { dealerId: i.currentInventoryOutOrder.consignmentDealerId }), r && (i.currentInventoryOutOrder.outWarehouseId = r.warehouseId)) : (i.currentInventoryOutOrder.consignmentDealerId = i.basicData.dealerWarehouses[0].dealerId, i.currentInventoryOutOrder.outWarehouseId = i.basicData.dealerWarehouses[0].warehouseId) : h.warn({ message: "当前诊所寄售仓库暂无寄售供应商" }));
                    k() },
                lt = function(n) { var t = this.dataItem(n.item.index());
                    i.currentInventoryOutOrder.outOrderAction !== r.OutOrderAction.TakeOut && i.currentInventoryOutOrder.outOrderAction !== r.OutOrderAction.SalesOut && t.grade === r.WarehouseGrade.Consignee.value && (n.preventDefault(), h.warn({ message: "非领用和销售出库不能选择寄售仓库" })) },
                at = function(n) { var r = n.item.context.innerText,
                        t = _.find(i.basicData.dealerWarehouses, { dealerName: r });
                    t && (i.currentInventoryOutOrder.outWarehouseId = t.warehouseId, k()) },
                k = function() { var n, t, u;
                    i.currentInventoryOutOrder && i.currentInventoryOutOrder.referenceOrderId > 0 && (n = 0, t = i.currentInventoryOutOrder.id, i.currentInventoryOutOrder.outOrderAction == r.OutOrderAction.TakeOut ? n = 1 : i.currentInventoryOutOrder.outOrderAction == r.OutOrderAction.SalesOut ? n = 2 : i.currentInventoryOutOrder.outOrderAction == r.OutOrderAction.ProcurementReturnOut && (n = 3), n > 0 && (t = i.currentInventoryOutOrder.referenceOrderId), u = { orderId: t, preOutOrderType: n }, i.getOutOrderDetail(u, i.currentInventoryOutOrder.outWarehouseId)) },
                vt = function(n) { var t, r; if (n.referenceOrderId) { if (t = _.filter(n.items, function(n) { return n.isChecked && n.unOutStorageNum > 0 }), t.length === 0) { l.error("请选择需要出库的物品!"); return } n.items = t } r = e.open({ title: "编辑出库单", titleIconClass: "iconfont icon-chuku1", template: "<inventory-out-order-edit-modal-view><\/inventory-out-order-edit-modal-view>", controller: "InventoryOutOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { outOrder: n } } } });
                    r.result.then(function() { i.$parent.onSearchOutOrderList ? w.go(".", { showOutOrderDetail: null }).then(function() { i.$parent.onSearchOutOrderList() }) : i.$parent.close() }) },
                yt = function(n) { var t = e.open({ title: "新增出库单", titleIconClass: "iconfont icon-chuku1", template: "<inventory-out-order-edit-modal-view><\/inventory-out-order-edit-modal-view>", controller: "InventoryOutOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { sourceOrderId: n } } } }); return t.result },
                pt = function(n, t) { var i = n.id;
                    o.publish(o.events.ProductSelected, i, t.delegateTarget) },
                wt = function(n) { var t = angular.copy(n);
                    s.printInventoryOutOrder(t, i) },
                bt = function(n) { var t = _.clone(n),
                        r; if (t.referenceOrderId) { if (r = _.filter(t.products, function(n) { return n.isChecked && n.unOutStorageNum > 0 }), r.length === 0) { l.error("请选择需要打印的物品!"); return } t.items = _.filter(r, function(n) { return n.unOutStorageNum > 0 && n.inventoryCount > 0 }) } s.printInventoryOutOrderWithRef(t, i) },
                kt = function(n) { var t = n.id;
                    c.viewOperationLog(t, "InventoryOutOrder") },
                dt = function(n) { f.open({ animation: !0, backdrop: "static", template: "<inventory-out-order-batch-dialog-view><\/inventory-out-order-batch-dialog-view>", controller: "InventoryOutOrderBatchDialogCtrl", windowClass: "ares-medium-modal-content inventory-out-order-batch-dialog-wrapper", backdropClass: "inventory-modal-backdrop", resolve: { host: function() { return { orderItem: angular.copy(n), isOnlyShow: 1, isInventoryCostVisible: i.uiState.isCostVisible } } } }) },
                gt = function() { var n = i.currentInventoryOutOrder;
                    _.each(n.items, function(n) { n.isChecked = i.uiState.isCheckedAll && n.batchTotalCount > 0 });
                    _.each(n.products, function(n) { n.isChecked = i.uiState.isCheckedAll && n.inventoryCount > 0 }) },
                ni = function(n) { var t = i.currentInventoryOutOrder;
                    _.each(t.items, function(t) { t.productId == n.id && (t.isChecked = n.isChecked) });
                    _.any(t.products, function(n) { return n.isChecked === !i.uiState.isCheckedAll }) && (i.uiState.isCheckedAll = !i.uiState.isCheckedAll) },
                ti = function(n) { if (n && !(n.referenceOrderId > 0)) { var t = e.open({ title: "编辑出库单", titleIconClass: "iconfont icon-chuku1", template: "<inventory-out-order-edit-modal-view><\/inventory-out-order-edit-modal-view>", controller: "InventoryOutOrderEditModalCtrl", confirmClose: !0, needActive: !0, resolve: { host: function() { return { sourceOrderId: n.id, isCancelAndCreate: !0 } } } });
                        t.result.then(function() { i.$parent.onSearchOutOrderList ? i.$parent.onSearchOutOrderList() : i.$parent.close() }) } },
                ii = function(n) { var t = angular.element(n.target);
                    t.popover("show") },
                d = function(i, r) { var u = t.defer(),
                        f = { orderid: i.orderId, preOutOrderType: i.preOutOrderType, warehouseId: r || 0 }; return a.getPreOutOrder(f).success(function(n) { g(n);
                        u.resolve(!0) }).error(function(t) { l.error("无法获取订单详情");
                        n.log(t);
                        u.reject() }), u.promise },
                g = function(n) { b(n);
                    i.currentInventoryOutOrder = angular.copy(n);
                    i.currentInventoryOutOrder.isBatchOutEnabled && (i.currentInventoryOutOrder.products = _.filter(n.products, function(n) { return n.inventoryCount > 0 && n.unOutStorageNum > 0 }), i.currentInventoryOutOrder.zeroProducts = _.filter(n.products, function(n) { return n.inventoryCount === 0 && n.unOutStorageNum > 0 }), i.currentInventoryOutOrder.finishedProducts = _.filter(n.products, function(n) { return n.unOutStorageNum === 0 }));
                    ft(i.currentInventoryOutOrder) },
                nt = function(n) { i.state === 0 ? d(n, null).then(function() { o.publish(o.events.IventoryOrderDetailRendered, null, "InventoryOutOrderListDetailCtrl") }) : (g(n), o.publish(o.events.IventoryOrderDetailRendered, null, "InventoryOutOrderListDetailCtrl")) };
            (function() { i.uiState = { isCostVisible: v.isInventoryCostAllowed, isCheckedAll: !0 };
                i.isInventoryCostVisible = v.isInventoryCostAllowed;
                i.onSelectProduct = pt;
                i.onEditOutOrder = vt;
                i.printOutOrder = wt;
                i.printOutOrderWithRef = bt;
                i.viewOperationLog = kt;
                i.showBatchItemDialog = dt;
                i.setOrderCheck = gt;
                i.checkOrderIsChecked = ni;
                i.onWarehouseChanged = ct;
                i.onCancelAndCreateOrder = ti;
                i.showExpressPopover = ii;
                i.onCopyOutOrder = yt;
                i.onWarehouseSelected = lt;
                i.onConsignmentDealerSelected = at;
                i.onCancelOutOrder = tt;
                i.reOutOrder = it;
                i.processOutOrder = rt;
                i.takeOrderClose = ut;
                i.getOutOrderDetail = d;
                i.formatOrder = b;
                i.isPatientRequireForOrder = ot;
                i.exportExcel = st;
                u.initBasicData(i).then(function() { nt(i.order) });
                i.$watch("order", function(n) { nt(n) }) })() } return n.$inject = ["$log", "$q", "$scope", "enums", "inventoryOutOrderUtil", "$modal", "aresModalShelf", "eventAggregator", "supplyChainPrintUtil", "aresConfirmDialog", "inventoryInOrderUtil", "aresNotification", "inventorySvc", "loginContext", "inventoryUtil", "$filter", "$state"], n }();
    supplychainModule.controller("InventoryOutOrderListDetailCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryTransferOrderListView", ["$q", "$timeout", "$window", "inventoryTransferOrderUtil", "tenantOptionSvc", function(n, t, i, r, u) { return { replace: !0, templateUrl: "/app/supplychain/views/inventory/inventory-transfer-order-list/inventory-transfer-order-list-view.html", controller: "InventoryTransferOrderListCtrl", link: function(f, e) { var c = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } },
                l = function() { u.getTenantOption("IsAcrossOfficeInventoryTransferEnabled").then(function(n) { f.isAcrossOfficeInventoryTransferEnabled = n;
                        s(); var t = angular.element(i);
                        t.on("resize", function() { s() });
                        f.initSearchData();
                        r.initBasicData(f).then(function() { f.initDefaultData() }) }) },
                s = function() { var r = angular.element(i).height(),
                        u = 110,
                        h = f.isAcrossOfficeInventoryTransferEnabled ? 6 : 5,
                        n, v, s;
                    f.searCondition && (u = 110 + h * 44); var l = r - u - 145,
                        t = e.find(".left-side-container .table-main .table-main-content");
                    t.height(l);
                    t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar(c); var o = r - 130,
                        a = e.find(".right-side-container .detail-list");
                    a.height(o);
                    n = e.find(".right-side-container .table-main .table-main-content");
                    v = 346;
                    s = o - 134 - e.find(".tit-head").height();
                    n.height(s);
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(c) },
                a = function(n, t) { var i = n.sender.value();
                    i != f.searchCriteria[t] && (f.searchCriteria[t] = i);
                    f.onSearchOrderList() },
                o = function(i, r) { var u = n.defer(); return f.page.pageIndex = i ? f.page.pageIndex : 1, f.searchOrderList().then(function() { t(function() { if (s(), f.pageData.items) { var n = 0;
                                r && (n = _.findIndex(f.pageData.items, { id: r }), n = n || 0, n === -1 && (n = 0));
                                h(f.pageData.items[n], n) } else f.order = "";
                            u.resolve() }) }), u.promise },
                v = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && o() },
                h = function(n, t) { n ? (f.triggerIndex = t, f.order = n) : f.order = null },
                y = function(n) { f.state = n;
                    f.initSearchData();
                    f.searchCriteria.state = n;
                    f.order = null;
                    o() },
                p = function(n) { var t = _.findIndex(f.pageData.items, { id: n }),
                        i;
                    t > -1 ? (i = t - 1, f.pageData.items.splice(t, 1), f.pageData.items.length > t ? h(f.pageData.items[t], t) : f.pageData.items.length > i && i > -1 ? h(f.pageData.items[i], i) : o()) : o() },
                w = function() { t(function() { var n = e.find("#toWarehouse").data("kendoDropDownList"),
                            t, i;
                        n && (n.dataSource.data(f.toWarehouses), t = _.find(f.toWarehouses, { isDefault: !0 }), i = t ? t.id : f.toWarehouses && f.toWarehouses.length > 0 ? f.toWarehouses[0].id : 0, n.value(i), f.searchCriteria.toWarehouseId = i) }) },
                b = function() { t(function() { var n = e.find("#receiver-drop").data("kendoDropDownList"),
                            t;
                        n && (n.dataSource.data(f.receivers), t = f.receivers && f.receivers.length > 0 ? f.receivers[0].id : 0, n.value(t), f.searchCriteria.receiverId = t) }) },
                k = function(n) { var t = n.sender.value();
                    t == 0 ? (f.toWarehouses = angular.copy(f.fromWarehouses), f.toWarehouses && f.toWarehouses[0] && (f.toWarehouses[0] = { id: 0, name: "调入仓库" }), f.selectedOfficeIdsArray = [], f.searchCriteria.toWarehouseId = 0) : (f.toWarehouses = [{ id: 0, name: "调入仓库" }], f.searchCriteria.toOfficeId = null, f.searchCriteria.toWarehouseId = 0);
                    f.onSearchOrderList() },
                d = function() { f.onSearchOrderList() };
            (function() { f.orderDetail = h;
                f.onSearchTimeRangeChanged = d;
                f.onSearchOrderList = o;
                f.onEnter = v;
                f.initTableView = s;
                f.onDropDownChange = a;
                f.switchState = y;
                f.selectedNextOrder = p;
                f.state = 0;
                f.setToWarehouseDropDownDataSource = w;
                f.setReceiverDropDownDataSource = b;
                f.onChangeTransferType = k;
                f.isAres3 = window.Ares3;
                l() })() } } }]);
supplychainModule.controller("InventoryTransferOrderListCtrl", ["$log", "$q", "$timeout", "eventAggregator", "$scope", "inventorySvc", "reportUtil", "multiOfficeDataDic", "inventoryTransferOrderUtil", function(n, t, i, r, u, f, e, o, s) { "use strict"; var h = function() { var n = t.defer(); return f.searchPreTransferOrder(v()).success(function(t) { u.pageData = t.page ? t.page : t;
                u.page.totalCount = u.pageData.totalCount;
                u.page.pageCount = u.pageData.pageCount || 1;
                u.pageData.items && angular.forEach(u.pageData.items, function(n) { s.formatOrder(n, u) });
                n.resolve() }), n.promise },
        v = function() { var n = angular.copy(u.searchCriteria); return n.pageIndex = u.page.pageIndex, n.pageSize = u.page.pageSize, n.operatorId && n.operatorId != "0" || (n.operatorId = null), n.fromWarehouseId && n.fromWarehouseId != "0" || (n.fromWarehouseId = null), n.toWarehouseId && n.toWarehouseId != "0" || (n.toWarehouseId = null), n.receiverId && n.receiverId != "0" || (n.receiverId = null), n.transfererId && n.transfererId != "0" || (n.transfererId = null), n.createdUserId && n.createdUserId != "0" || (n.createdUserId = null), n.toOfficeId && !n.toWarehouseId && (n.toWarehouseIds = _.pluck(_.filter(u.toWarehouses, function(n) { return n.id }), "id")), n.startDate = moment(u.searchTimeRange.startDate).isValid() ? moment(u.searchTimeRange.startDate).format("YYYY-MM-DD") : "", n.endDate = moment(u.searchTimeRange.endDate).isValid() ? moment(u.searchTimeRange.endDate).add(1, "days").format("YYYY-MM-DD") : "", n.state = u.state, n },
        a = function() { c();
            u.searchCriteria.state = u.state;
            h().then(function() { i(function() { if (u.menuChangedData) { if (u.menuChangedData && u.menuChangedData.id) { var n = 0,
                                t = _.find(u.pageData.items, function(t, i) { return n = i, t.orderId === u.menuChangedData.id || t.id === u.menuChangedData.id });
                            t && u.orderDetail(t, n) } } else u.pageData.items[0] ? u.orderDetail(u.pageData.items[0], 0) : (u.order = "", u.state = 1, c(), u.onSearchOrderList());
                    u.initTableView() }) }) },
        c = function() { if (u.searchCriteria = { state: 0, orderNumber: null, fromWarehouseId: 0, toWarehouseId: 0, receiverId: 0, transfererId: 0, createdUserId: 0, orderType: 0 }, u.toWarehouses = angular.copy(u.fromWarehouses), u.toWarehouses && u.toWarehouses[0] && (u.toWarehouses[0] = { id: 0, name: "调入仓库" }), u.selectedOfficeIdsArray = [], u.state === 0) u.searchTimeRange = { startDate: "", endDate: "" };
            else { var n = e.getDefaultTimeSpan();
                u.searchTimeRange = { startDate: u.searchTimeRange.startDate || moment(n.startTime).format("YYYY-MM-DD"), endDate: u.searchTimeRange.endDate || moment(n.endTime).format("YYYY-MM-DD") } } u.searchCriteria.startDate = u.searchTimeRange.startDate;
            u.searchCriteria.endDate = u.searchTimeRange.endDate },
        l = function(n) { u.menuChangedData = n;
            u.state = n.state;
            u.triggerIndex = null;
            a() },
        y = function() { r.subscribe(u, r.events.IventoryTransferOrderCreated, function(n, t) { u.menuChangedData = t;
                l(t) });
            r.subscribe(u, r.events.IventoryActionMenuChanged, function(n, t) { u.menuChangedData = t;
                l(t) });
            r.subscribe(u, r.events.IventoryOrderDetailRendered, function() { u.initTableView() }) },
        p = function(n) { u.searchCriteria.toOfficeId = n[0].id;
            u.selectedOfficeIdsArray = [u.searchCriteria.toOfficeId];
            t.all([o.loadDic(u.searchCriteria.toOfficeId, "warehouseDic").then(function(n) { u.toWarehouses = n || [];
                u.toWarehouses.unshift({ id: 0, name: "调入仓库" });
                u.setToWarehouseDropDownDataSource() }), o.loadDic(u.searchCriteria.toOfficeId, "currentOfficeWorkProviderDic").then(function(n) { u.receivers = n || [];
                u.receivers.unshift({ id: 0, name: "全部收货人" });
                u.setReceiverDropDownDataSource() })]).then(function() { i(function() { h() }) }) };
    (function() { u.page = { pageIndex: 1, pageSize: 20 };
        u.searchTimeRange = { startDate: "", endDate: "" };
        u.searchOrderList = h;
        u.initDefaultData = a;
        u.initSearchData = c;
        u.positioningTab = l;
        u.onOfficeSelected = p;
        y() })() }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r) { var u = this;
            this.$modal = n;
            this.eventAggregator = t;
            this.inventoryInOrderUtil = i;
            this.aresModalShelf = r;
            this.restrict = "E";
            this.replace = !0;
            this.scope = { order: "=", state: "=" };
            this.templateUrl = "/app/supplychain/views/inventory/inventory-transfer-order-list/components/inventory-transfer-order-detail-view.html";
            this.controller = "InventoryTransferOrderDetailCtrl";
            this.link = function(n) { var t = u,
                    i = function(n, i) { var r = n.product.id;
                        t.eventAggregator.publish(t.eventAggregator.events.ProductSelected, r, i.delegateTarget) },
                    r = function(n) { t.$modal.open({ animation: !0, backdrop: "static", template: "<transfer-order-item-batch-view><\/transfer-order-item-batch-view>", controller: "TransferOrderItemBatchCtrl", windowClass: "ares-medium-modal-content product-batch-wider", resolve: { host: function() { return { orderItem: angular.copy(n) } } } }) },
                    f = function(n) { t.inventoryInOrderUtil.viewOperationLog(n.id, "InventoryTransferOrder") },
                    e = function() { var i = t.aresModalShelf.open({ title: "编辑调拨单", titleIconClass: "iconfont icon-zhuanhuan", template: "<inventory-transfer-order-edit-modal-view><\/inventory-transfer-order-edit-modal-view>", controller: "InventoryTransferOrderEditModalCtrl", needActive: !0, resolve: { host: function() { return { orderId: n.currentOrder.id, fromWarehouseId: n.currentOrder.warehouseId } } }, confirmClose: !0 });
                        i.result.then(function(t) { if (t)
                                if (n.$parent.onSearchOrderList) n.$parent.onSearchOrderList(null, t.id);
                                else n.$parent.close() }) };
                (function() { n.onEditOrder = e;
                    n.onSelectedProduct = i;
                    n.showBatchItemDialog = r;
                    n.viewOperationLog = f })() } } return n.$inject = ["$modal", "eventAggregator", "inventoryInOrderUtil", "aresModalShelf"], n }();
    supplychainModule.directive("inventoryTransferOrderDetailView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l) { var a = function(i) { var r = t.defer(); return f.getTransferOrder(i).success(function(n) { g(n);
                        r.resolve(!0) }).error(function(t) { u.error("无法获取订单详情");
                        n.log(t);
                        r.reject() }), r.promise },
                p = function(n) { if (n) { var t = angular.copy(n);
                        c.formatOrder(t, r);
                        v(t);
                        e.printInventoryTransferOrder(t, r) } },
                v = function(n) { var t = [];
                    angular.forEach(n.items, function(n) { angular.forEach(n.batchs, function(n) { t.push(n) }) });
                    n.items = t },
                w = function() { Ares.ensureNotDuplicated("InventoryTransferOrderApproveCheck") && s.warn({ message: "您确定执行该单据吗？单据执行后库存将发生变更", onConfirm: function() { f.approveTransferOrder(r.currentOrder.id).success(function() { i.publish(i.events.RefreshIventoryHint, null, "InventoryTransferOrderDetailCtrl");
                                u.success("调拨成功!");
                                Ares.sensors.track("InventoryOperation", { OrderNumber: r.currentOrder.orderNumber, OperationType: "调拨", OperationMode: "调拨执行" });
                                r.$parent.selectedNextOrder ? r.$parent.selectedNextOrder(r.currentOrder.id) : r.$parent.close() }).error(function(n) { n.name == "InventoryOperationException" || n.name == "NotInOrderInformationException" ? s.warn({ message: n.message }) : u.error("调拨失败!") }) }, onCancel: function() {} }) },
                b = function() { if (r.currentOrder && Ares.ensureNotDuplicated("InventoryTransferOrderCancelCheck")) { var t = r.currentOrder.orderNumber,
                            n = r.currentOrder.id;
                        s.warn({ message: "该单据已关联其他单据，作废后相关单据也会被作废，是否确定作废", onConfirm: function() { f.cancelTransferOrder(n).success(function() { u.success("作废成功!");
                                    Ares.sensors.track("InventoryOperation", { OrderNumber: t, OperationType: "调拨", OperationMode: "作废" });
                                    r.menuChangedData = { id: n, state: 2 };
                                    r.$parent.positioningTab ? r.$parent.positioningTab(r.menuChangedData) : r.$parent.close() }).error(function(n) { n.name === "ArgumentException" || n.name === "InventoryOperationException" ? u.error(n.message) : u.error("作废失败") }) }, onCancel: function() {} }) } },
                k = function(n) { var i, u, s, l; if (n) { i = angular.copy(n);
                        c.formatOrder(i, r);
                        v(i); var f = d(i),
                            t = [],
                            e = { columnSettings: [70, 90, 150, 60, 200, 60, 80, 80, 100, 200, 100], title: "调拨单" + i.orderNumber, fileName: "调拨单" + i.orderNumber, headerRow: { value: "库存调拨单", colSpan: 11 }, contentRow: [] };
                        e.contentRow.push({ row: [{ cellType: "headerCell", value: "调拨类型：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.orderType == 1 ? "跨机构调拨" : "机构内调拨", colSpan: 2, textAlign: "left" }, { cellType: "headerCell", value: "机构名称：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: f.officeName, colSpan: 2, textAlign: "left" }, { cellType: "headerCell", value: "调出仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.fromWarehouseName, colSpan: 4, textAlign: "left" }] });
                        e.contentRow.push({ row: [{ cellType: "headerCell", value: "调入仓库：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.toWarehouseName, colSpan: 2, textAlign: "left" }, { cellType: "headerCell", value: "调拨单号：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.orderNumber, colSpan: 2, textAlign: "left" }, { cellType: "headerCell", value: "单据日期：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: h("toDateString")(i.orderDate), colSpan: 4, textAlign: "left" }] });
                        t = [].concat([{ cellType: "headerCell", value: "制单人：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.createUserName, colSpan: 2, textAlign: "left" }, { cellType: "headerCell", value: "备注：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.notes, colSpan: i.orderType == 1 ? 2 : 7, textAlign: "left" }]);
                        i.orderType == 1 && (t = t.concat([{ cellType: "headerCell", value: "收入单位：", colSpan: 1, textAlign: "left" }, { cellType: "regularCell", value: i.toOfficeName, colSpan: 4, textAlign: "left" }]));
                        e.contentRow.push({ row: t });
                        t = [];
                        u = 0;
                        t.push({ cellType: "headerCell", value: "序号" });
                        u += 1;
                        r.productCodeOptions.allowInsideCode && (t.push({ cellType: "headerCell", value: "内部编码" }), u += 1);
                        s = 1 + (r.productCodeOptions.allowInsideCode ? 0 : 1);
                        t.push({ cellType: "headerCell", value: "名称", colSpan: s }, { cellType: "headerCell", value: "品牌" }, { cellType: "headerCell", value: "规格" }, { cellType: "headerCell", value: "单位" }, { cellType: "headerCell", value: "调拨数量" });
                        u += 4 + s;
                        f.isBatchNumberVisible && (t.push({ cellType: "headerCell", value: "批号" }), u += 1);
                        f.isExpireDateVisible && (t.push({ cellType: "headerCell", value: "有效期至" }), u += 1);
                        f.isUnicodeVisible && (t.push({ cellType: "headerCell", value: "唯一码" }), u += 1);
                        t.push({ cellType: "headerCell", value: "备注", colSpan: 11 - u });
                        e.contentRow.push({ row: t });
                        _.each(i.items, function(n, i) { t = [];
                            t.push({ cellType: "centerCell", value: i + 1 });
                            r.productCodeOptions.allowInsideCode && t.push({ cellType: "centerCell", value: n.code });
                            t.push({ cellType: "regularCell", value: n.name, colSpan: s });
                            t.push({ cellType: "regularCell", value: n.producer });
                            t.push({ cellType: "regularCell", value: n.specification });
                            t.push({ cellType: "centerCell", value: n.unit });
                            t.push({ cellType: "numberCell", value: n.count });
                            f.isBatchNumberVisible && t.push({ cellType: "centerCell", value: n.batchNumber });
                            f.isExpireDateVisible && t.push({ cellType: "centerCell", value: h("toDateString")(n.expiredDate) });
                            f.isUnicodeVisible && t.push({ cellType: "centerCell", value: n.unicode });
                            t.push({ cellType: "regularCell", value: n.notes, colSpan: 11 - u });
                            e.contentRow.push({ row: t }) });
                        t = [];
                        t.push({ cellType: "headerCell", value: "合计", colSpan: 6, textAlign: "left" });
                        t.push({ cellType: "numberCell", value: f.totalCount, colSpan: 1 });
                        t.push({ cellType: "regularCell", value: "", colSpan: 4 });
                        e.contentRow.push({ row: t });
                        l = "发货人：" + i.transfererName + "            发货人签字：            收货人：" + i.receiverName + "            收货人签字:";
                        e.contentRow.push({ row: [{ cellType: "regularCell", value: "", colSpan: 1 }, { cellType: "headerCell", value: l, colSpan: 10, textAlign: "left" }] });
                        o.exportExcel(e) } },
                d = function(n) { var t = {},
                        e;
                    n.officeId && (e = r.offices.find(function(t) { return t.id == n.officeId }), t.officeName = e.name); var o = 0,
                        i = !1,
                        u = !1,
                        f = !1; return n.items.forEach(function(n) { o += n.count;
                        i = i || n.expiredDate;
                        u = u || n.batchNumber;
                        f = f || n.unicode }), t.totalCount = o, t.isExpireDateVisible = i, t.isBatchNumberVisible = u, t.isUnicodeVisible = f, t },
                g = function(n) { var t; if (n) { t = angular.copy(n);
                        t.items = []; var u = angular.copy(_.filter(n.items, function(n) { return n.count > 0 })),
                            i = _.groupBy(u, "productId"),
                            f = _.keys(i);
                        angular.forEach(f, function(n) { var r = i[n],
                                u = [],
                                f = 0,
                                e;
                            angular.forEach(r, function(n) { var t = angular.copy(n);
                                f += t.count;
                                u.push(t) });
                            e = { product: r[0].product, batchs: u, count: f, notes: r[0].notes };
                            t.items.push(e) });
                        c.formatOrder(t, r);
                        r.order && (t.fromWarehouseName = r.order.fromWarehouseName, t.toWarehouseName = r.order.toWarehouseName);
                        r.currentOrder = t } },
                y = function(n) { n ? a(n.id).then(function() { i.publish(i.events.IventoryOrderDetailRendered, null, "InventoryTransferOrderDetailCtrl") }) : r.currentOrder = null };
            (function() { r.getOrderDetail = a;
                r.printOrder = p;
                r.onCancelOrder = b;
                r.onApproveOrder = w;
                r.exportExcel = k;
                l.getTenantOption("IsAcrossOfficeInventoryTransferEnabled").then(function(n) { r.isAcrossOfficeInventoryTransferEnabled = n;
                    c.initBasicData(r).then(function() { y(r.order) });
                    r.$watch("order", function(n) { y(n) }) }) })() } return n.$inject = ["$log", "$q", "eventAggregator", "$scope", "aresNotification", "inventorySvc", "supplyChainPrintUtil", "inventoryUtil", "aresConfirmDialog", "$filter", "inventoryTransferOrderUtil", "tenantOptionSvc"], n }();
    supplychainModule.controller("InventoryTransferOrderDetailCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("inventoryProcurementApplyListView", ["$log", "$q", "$timeout", "aresDialog", "appNav", "$modal", "aresSlidePanel", "$window", "aresNotification", "enums", "eventAggregator", "dataDicSvc", "officeUtil", "loginContext", "aresConfirmDialog", "aresModalShelf", "procurementApplyOrderUtil", "supplyChainPrintUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b) { return { restrict: "E", templateUrl: "/app/supplychain/views/procurement/inventory-procurement-apply-list-view.html", controller: "InventoryProcurementApplyListCtrl", link: function(n, u) { var l = u.find(".table-main"),
                a = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } },
                k = function() { e();
                    angular.element(o).on("resize", e);
                    u.on("$destroy", function() { angular.element(o).off("resize", e) }) },
                e = function() { i(function() { var n = angular.element(o).height();
                        l.height(n - 225);
                        l.data("mCustomScrollbarIndex") ? l.mCustomScrollbar("update") : l.mCustomScrollbar(a) }, 0, !1) },
                d = function() { moment(n.searchCriteria.startDate).isAfter(moment(n.searchCriteria.endDate)) && (n.searchCriteria.endDate = n.searchCriteria.startDate);
                    f() },
                g = function(t) { n.searchCriteria.productIds = t ? t.products ? _.pluck(t.products, "id") : [t.id] : null;
                    f() },
                nt = function(n, t) { var i = n.productId;
                    c.publish(c.events.ProductSelected, i, t.delegateTarget) },
                tt = function(n) { var t = window.event ? n.keyCode : n.which;
                    t === 13 && f() },
                f = function() { var r = t.defer(); return n.searchProcurementApply().then(function() { i(function() { e();
                            r.resolve() }, 0, !1) }), r.promise },
                it = function() { var n = p.open({ template: "<procurement-apply-order-edit-modal-view><\/procurement-apply-order-edit-modal-view>", controller: "ProcurementApplyOrderEditModalCtrl", title: "新增采购申请", titleIconClass: "iconfont icon-caigouoff", resolve: { dataHost: function() { return { procurementApply: null } } }, confirmClose: !0 });
                    n.result.then(function() { f() }) },
                rt = function(t) { n.getApplyDetail(t).then(function(n) { var t = p.open({ template: "<procurement-apply-order-edit-modal-view><\/procurement-apply-order-edit-modal-view>", controller: "ProcurementApplyOrderEditModalCtrl", title: "编辑采购申请", titleIconClass: "iconfont icon-caigouoff", resolve: { dataHost: function() { return { procurementApply: n } } } });
                        t.result.then(function() { f() }) }) },
                ut = function(t) { n.getApplyDetail(t).then(function(n) { n.status = h.ProcurementApplyStatus.Pending;
                        n.id = null;
                        n.orderNo = null; var t = p.open({ template: "<procurement-apply-order-edit-modal-view><\/procurement-apply-order-edit-modal-view>", controller: "ProcurementApplyOrderEditModalCtrl", title: "新增采购申请", titleIconClass: "iconfont icon-caigouoff", resolve: { dataHost: function() { return { procurementApply: n } } } });
                        t.result.then(function() { f() }) }) },
                ft = function(t) { y.confirm({ message: "确定作废当前采购申请？" }).then(function() { n.cancelProcurementApply(t) }) },
                et = function(t) { y.warn({ message: "确定提交审批此申请单？", onConfirm: function() { n.submitWorkflowProcurementApply(t).then(function() { f() }) }, onCancel: function() {} }) },
                ot = function() { k();
                    n.initDefaultData().then(function() { f() }) },
                st = function() { i(function() { u.find("[data-toggle=tooltip]").tooltip() }, 0, !1) },
                ht = function(n) { w.exportExcel(n) },
                ct = function(t) { b.printProcurementApplyOrder(t, n) },
                lt = function() { n.procurementApplyTotalCount <= 0 || n.invokeApplyOrderListToZip().then(function(n) { r.info("信息", n) }, function() { s.error("列表导出失败，请重试！") }) };
            (function() { n.isHideAddOrderBtn = v.isGroup && !v.isRootGroup && v.officeType === 1;
                n.onSearchDateChanged = d;
                n.onEnter = tt;
                n.initTableView = e;
                n.onSelectProduct = nt;
                n.onSearchProduct = g;
                n.onSearchProcurementApply = f;
                n.newProcurementApply = it;
                n.onCancelApply = ft;
                n.editProcurementApply = rt;
                n.reCreateProcurementApply = ut;
                n.onSubmitWorkflowProcurementApply = et;
                n.refreshTooltips = st;
                n.exportExcel = ht;
                n.printApplyOrder = ct;
                n.triggerApplyOrderListToZip = lt;
                ot() })() } } }]);
supplychainModule.directive("inventoryProcurementReturnOrderListView", ["$log", "$q", "$timeout", "$window", "aresNotification", "eventAggregator", "aresSlidePanel", "dataDicSvc", "$modal", "$state", "enums", "appNav", "loginContext", "inventoryUtil", "supplyChainPrintUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { return { restrict: "E", templateUrl: "/app/supplychain/views/procurement/inventory-procurement-return-order-list-view.html", controller: "InventoryProcurementReturnOrderListCtrl", link: function(n, e) { var k = function() { w(); var t = angular.element(r);
                    e.find(".list-tabel-wrap .table-main-list").mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                    t.on("resize", function() { w() });
                    ot().then(function() { n.initDefaultData() }) },
                w = function() { var t = angular.element(r).height(),
                        i = t - 225 - (window.Ares3 ? 20 : 0),
                        u = i - 74,
                        n = e.find(".list-tabel-wrap .table-main-list");
                    n.height(u);
                    n.mCustomScrollbar("update") },
                d = function(t) { n.searchCriteria = t;
                    p() },
                g = function(t) { var i = n.searchCriteria,
                        o = t.sender.value(),
                        s = moment(o).startOf("day"),
                        e = moment(i.startDate).startOf("day"),
                        r = moment(i.endDate).startOf("day"),
                        f; if (r.diff(s) && (i.endDate = r.toDate()), e.isAfter(r)) { f = e.toDate();
                        t.sender.value(f);
                        i.endDate = f;
                        u.error("截止时间不能小于起始时间");
                        p(); return } p() },
                p = function() { var r = t.defer(); return n.searchProcurementReturnOrder().then(function() { i(function() { w();
                            r.resolve() }) }), r.promise },
                nt = function(t) { n.selectedOfficeIdsArray = _.pluck(t, "officeId");
                    n.searchProcurementReturnOrder() },
                tt = function(n, t) { var i = n.productId || item.id;
                    f.publish(f.events.ProductSelected, i, t.delegateTarget) },
                it = function(t) { var i = t.sender.value();
                    i != n.searchCriteria.status && (n.searchCriteria.status = i);
                    p() },
                rt = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && p() },
                ut = function(t, i) { i.procurementOrderItem.returnApplyOrder = t.returnApplyOrder; var r = s.open({ animation: !0, backdrop: "static", template: "<procurement-return-order-edit-dialog-view><\/procurement-return-order-edit-dialog-view>", controller: "ProcurementReturnOrderEditDialogCtrl", windowClass: "procurement-retrun-order-dialog-wrap", resolve: { host: function() { return { payOrderItem: i.procurementOrderItem, isLinkedCare: !0 } } } });
                    r.result.then(function(i) { i && t && t.returnApplyOrder && t.returnApplyOrder.serviceOrderNo && t.returnApplyOrder.status !== c.ProcurementReturnApplyStatus.Returned ? b(t) : n.searchProcurementReturnOrder() }) },
                ft = function(n) { h.go("supplychain.inventory.outorder", { showOutOrderDetail: { id: n.id, preOutOrderType: 3, state: 0 } }) },
                et = function(t) { y.printProcurementReturnOrder(t, n) },
                ot = function() { var i = t.defer(); return o.dealerDic.loadActive().then(function(t) { n.currentSupplier = "供应商";
                        t.unshift({ name: n.currentSupplier });
                        n.suppliers = t;
                        i.resolve(!0) }), i.promise },
                st = function(n, t, i) { t.stopPropagation();
                    i ? n.isShowServiceOrderNo = !n.isShowServiceOrderNo : n.isShowPayOrderNo = !n.isShowPayOrderNo },
                ht = function(n, t, i) { t.stopPropagation();
                    i ? n.isShowServiceOrderNo = !n.isShowServiceOrderNo : n.isShowPayOrderNo = !n.isShowPayOrderNo },
                b = function(n) { var t = { action: c.ProcurementMallAction.ServiceOrder, serviceSn: n.returnApplyOrder.serviceOrderNo };
                    l.goToState("mallCenter", t) };
            (function() { n.groupSalesEnabled = !1;
                n.isGroup = a.isGroup;
                n.currentOfficeId = a.officeId;
                n.onChangeStartDate = d;
                n.onChangeEndDate = g;
                n.onChangeStatus = it;
                n.onEnter = rt;
                n.initTableView = w;
                n.onSelectProduct = tt;
                n.createOutOrder = ft;
                n.createReturnOrder = ut;
                n.onOfficeSelected = nt;
                n.printReturnOrder = et;
                n.moveToTips = st;
                n.leaveToTips = ht;
                n.onSearchProcuementReturnOrder = p;
                n.goToMallServiceDetail = b;
                n.loadOffices().then(function() { v.getGroupProcurementConfigs().then(function(t) { n.groupSalesEnabled = t.groupSalesEnabled;
                        k() }) }) })() } } }]);
supplychainModule.directive("inventoryProcurementReturnOrderOutItemDialogView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "aresNotification", "moduleOptionProvider", "loginContext", function(n, t, i, r, u, f, e, o) { return { replace: !0, templateUrl: "/app/supplychain/views/procurement/inventory-procurement-return-order-out-item-dialog-view.html", link: function(n, t) { var u = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 50) },
                r = function(t) { i(function() {
                        (t.returnCount = parseFloat(t.returnCount), isNaN(t.returnCount)) || (t.returnCount > t.count && (t.returnCount = t.count), n.returnOrderItem.outCount = n.getReturnOrderItemSumCount(), n.returnOrderItem.hasPassed = n.returnOrderItem.outCount == n.returnOrderItem.count) }) },
                f = function(n) { var t = n.keyCode;
                    (t < 48 || t > 57) && t != 8 && n.preventDefault() },
                e = function(n) { i(function() { n.returnCount = parseFloat(n.returnCount);
                        isNaN(n.returnCount) && (n.returnCount = 0, r(n)) }) },
                s = function(n, t) { i(function() { n.returnCount = parseFloat(n.returnCount);
                        n.returnCount = n.returnCount + t;
                        n.returnCount < 0 ? n.returnCount = 0 : r(n) }) };
            (function() { n.isInventoryCostVisible = o.isInventoryCostAllowed;
                n.onChangeReturnCount = r;
                n.onListenNumber = f;
                n.onBlurNumber = e;
                n.onEditReturnCount = s;
                u() })() } } }]);
supplychainModule.directive("procurementAssistanceListView", ["$timeout", "$window", "$document", "$sce", "$modal", "$state", "eventAggregator", "aresNotification", "aresSlidePanel", "enums", "procurementSvc", "officeUtil", "loginContext", "aresModalShelf", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { "use strict"; return { restrict: "E", templateUrl: "/app/supplychain/views/procurement/procurement-assistance-list-view.html", controller: "ProcurementAssistanceListCtrl", link: function(i, u) { var y = _.extend({}, { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } }, { callbacks: { whileScrolling: function(n) { var t = u.find("div.assistance-table-body-wrapper");
                            t.find(".sku-supplier-price-dropdown-anchor").popover("hide");
                            t.find(".icon-xinxi1").popover("hide");
                            n.topPct >= 90 && i.search() } } }),
                d = function() { var r = angular.element(t).height(),
                        n;
                    i.categorySelectHeight = r - 170;
                    n = r - 288;
                    u.find("div.assistance-table-body-wrapper").css("max-height", n + "px").mCustomScrollbar(y);
                    i.pageSize = Math.round(n / 50) + 5 },
                p = function() { var n = u.find("div.assistance-table-body-wrapper"),
                        r = n.find("div.assistance-table-body-container"),
                        t = u.find("div.assistance-table-footer");
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(y);
                    r.height() > n.height() ? t.addClass("fixed") : t.removeClass("fixed");
                    u.find("#checkbox-all-products").prop("checked", i.checkAll);
                    u.find("#checkbox-all-products-footer").prop("checked", i.checkAll);
                    window.Ares3 && t.width() > r.width() && t.addClass("submenu-visible") },
                g = function(n) { i.selCategory = n;
                    i.selectedCategoryIds = n.id === 0 ? [] : [n.id].concat(_.map(n.items, function(n) { return n.id }));
                    i.newSearch() },
                nt = function(n, t) { var i = n.productId;
                    e.publish(e.events.ProductSelected, i, t.delegateTarget) },
                tt = function() { if (i.checkAll) { var n = i.checkedProductCount = _.filter(i.productList, function(n) { return !n.procurementChecked }).length;
                        i.checkedProductCount = i.totalCount - n } else i.checkedProductCount = _.filter(i.productList, function(n) { return n.procurementChecked }).length },
                w = function() { return i.checkAll = !1, i.checkedProductCount = 0, i.nextPageIndex = 1, i.search() },
                it = function() { _.each(i.productList, function(n) { n.procurementChecked = i.checkAll });
                    i.checkedProductCount = i.checkAll ? i.totalCount : 0 },
                rt = function(n) { return i.isProcurementPriceLockEnabled || n.supplierType === 1 || n.supplierType === 2 },
                ut = function(t) { if (i.isEditing) { o.error("请先保存正在编辑的项目！"); return } i.currentEditProduct = angular.copy(t);
                    i.currentEditProduct.currentId = i.currentEditProduct.currentId || i.currentEditProduct.productId;
                    i.currentEditProduct.productId = t.procurementProductId;
                    i.currentEditProduct.isSyncToDealer = !0;
                    i.currentEditProduct.breadcrumbHtml = ht(t);
                    t.isEditing = !0;
                    i.isEditing = !0;
                    n(function() { p() }) },
                ft = function(n) { n.isEditing = !1;
                    i.isEditing = !1 },
                et = function(n) { i.currentEditProduct.supplier = n.dealerName;
                    i.currentEditProduct.supplierId = n.dealerId;
                    i.currentEditProduct.supplierType = n.dealerType;
                    i.currentEditProduct.price = n.price.toFixed(2) },
                ot = function(n) { i.getProductsBySpuId(n).then(function(t) { var r = v.open({ title: "库存预警设置", template: "<product-warn-rule-config-view><\/product-warn-rule-config-view>", controller: "ProductWarnRuleConfigCtrl", resolve: { host: function() { return { productUnityId: n, products: t } } } });
                        r.result.then(function() { i.search().then(function() { var t = i.currentEditProduct.currentId,
                                    n = _.find(i.productList, function(n) { return n.productId === t });
                                n ? (i.currentEditProduct = angular.copy(n), i.currentEditProduct.isSyncToDealer = !0, i.isEditing = !0, n.isEditing = !0) : i.isEditing = !1 }) }) }, function() { o.error("获取物品详情出错") }) },
                st = function(n) { n.keyCode === 13 && i.newSearch() },
                ht = function(n) { var u, t, f; if (!n.category) return ""; if (n.categoryId === 0) return '<span style="color: #00A6C9;">' + n.category + "<\/span>"; for (u = [], t = i.categoryNodeMap[n.categoryId]; t;) u.push(t.name), t = i.categoryNodeMap[t.parentId]; return f = "", _.each(u.reverse(), function(n, t) { f += t !== u.length - 1 ? n + "-" : '<span style="color: #00A6C9;">' + n + "<\/span>" }), r.trustAsHtml(f) },
                ct = function() { if (i.checkAll) i.search({ getAll: !0 }).then(function(n) { var t = _.map(_.filter(i.productList, function(n) { return !n.procurementChecked }), function(n) { return n.productId }),
                            r = _.filter(n, function(n) { return t.indexOf(n.productId) < 0 });
                        b(r) });
                    else { var n = i.productList.filter(function(n) { return n.procurementChecked }); if (!n || n.length == 0) { o.error("请选择需要采购的物品。"); return } b(n) } },
                b = function(n) { var r, t, u; if (n.forEach(function(n) { if ((i.isProcurementPriceLockEnabled || n.supplierType === 1 || n.supplierType === 2) && n.price <= 0) { r = "物品【" + n.productName + "】没有设置供应商报价，不能添加到采购单明细"; return } }), r) { o.error(r); return } t = [];
                    n.forEach(function(n) { var i = t.find(function(t) { return t.productId === n.procurementProductId }),
                            r;
                        i ? i.number += n.recommendedProcurementCount : (r = { productId: n.procurementProductId, barCode: n.procurementProductBarCode, planNumber: null, name: n.productName, price: n.price, number: n.recommendedProcurementCount, totalPrice: null, producer: n.producer, specification: n.procurementSpecification, unit: n.procurementUnit, isSynchronizeSupplier: !1 }, t.push(r)) });
                    u = v.open({ title: "新增采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-edit-modal-view><\/procurement-order-edit-modal-view>", controller: "ProcurementOrderEditModalCtrl", resolve: { dataHost: function() { return { procurementPayOrderProductItems: t, source: h.ProcurementPayOrderSource.PurchaseAssistant } } }, confirmClose: !0 });
                    u.result.then(function(n) { n && angular.isString(n) && at(n);
                        i.newSearch() }) },
                lt = function() { if (i.checkAll) i.search({ getAll: !0 }).then(function(n) { var t = _.map(_.filter(i.productList, function(n) { return !n.procurementChecked }), function(n) { return n.productId }),
                            r = _.filter(n, function(n) { return t.indexOf(n.productId) < 0 });
                        k(r) });
                    else { var n = i.productList.filter(function(n) { return n.procurementChecked }); if (!n || n.length == 0) { o.error("请选择需要采购的物品。"); return } k(n) } },
                k = function(n) { var f = [],
                        t = {},
                        r, u;
                    _.each(n, function(n) { t[n.procurementProductId] ? t[n.procurementProductId].count += n.recommendedProcurementCount : (f.push(n.procurementProductId), t[n.procurementProductId] = { productId: n.procurementProductId, name: n.productName, pinyin: n.pinyin, specification: n.procurementSpecification, producer: n.producer, unit: n.procurementUnit, code: n.code, barCode: n.barCode, category: n.category, count: n.recommendedProcurementCount }) });
                    r = _.values(t);
                    u = !1;
                    i.getProductsInventoryCount(f).then(function(n) { n && _.each(r, function(t) { var i = n.find(function(n) { return n.productId == t.productId });
                            i ? (t.curOfficeInventoryCount = i.curOfficeInventoryCount, t.rootOfficeInventoryCount = i.rootOfficeInventoryCount) : (t.curOfficeInventoryCount = 0, t.rootOfficeInventoryCount = 0);
                            t.rootOfficeInventoryCount > 0 && (u = !0) }); var t = { id: null, notes: "", items: r, applyTime: moment().format("YYYY-MMM-DD HH:mm:ss"), applicantId: a.userId, applicantName: a.userName, status: h.ProcurementApplyStatus.Pending, rootOfficeInventoryEnabled: u },
                            f = v.open({ template: "<procurement-apply-order-edit-modal-view><\/procurement-apply-order-edit-modal-view>", controller: "ProcurementApplyOrderEditModalCtrl", title: "新增采购申请", titleIconClass: "iconfont icon-caigouoff", resolve: { dataHost: function() { return { procurementApply: t } } } });
                        f.result.then(function() { i.newSearch() }) }) },
                at = function(n) { var t = s.open("<procurement-order-mall-cart-view><\/procurement-order-mall-cart-view>", "ProcurementOrderMallCartCtrl", { dataHost: function() { return { payOrderNo: n.split(":")[0], ownerOfficeId: n.split(":")[1] } } }, i);
                    t.result.then(function(n) { n && n.isOrderDone && i.newSearch() }) },
                vt = function() { f.go("supplychain.procurement.order", { openEditModalDirectly: !0 }) },
                yt = function() { l.getGroupProcurementMethod().then(function(n) { i.selfProcurementEnabled = n !== "group" || a.isRootGroup }) },
                pt = function(n, t) { i.recommendedCountDetail = {}; var r = angular.element(t.target);
                    r.popover("show");
                    c.getRecommendedCountDetails([n.productId]).success(function(n) { var t = n[0];
                        t.preInventoryOutSum = _.reduce(t.preInventoryOutDetails, function(n, t) { return n + t.count }, 0);
                        i.recommendedCountDetail = t }) },
                wt = function(n) { var i = angular.element(n.target),
                        r = i.data("bs.popover").$tip,
                        u = r.find(".arrow"),
                        f;
                    r.css({ padding: "10px", borderColor: "#00a6c9", borderRadius: 0 });
                    f = angular.element(t).height() - i.offset().top;
                    f < 300 ? (i.data("bs.popover").options.placement = "top", u.css({ borderTopColor: "#00a6c9" })) : (i.data("bs.popover").options.placement = "bottom", u.css({ borderBottomColor: "#00a6c9" })) },
                bt = function() { e.subscribe(i, e.events.sidebarSubMenuToggle, function(n, t) { var i = u.find("div.assistance-table-footer");
                        t.subMenuVisible ? i.addClass("submenu-visible") : i.removeClass("submenu-visible") }) };
            (function() { bt();
                d();
                i.checkAll = !1;
                i.checkedProductCount = 0;
                i.isEditing = !1;
                i.onProductCategoryChange = g;
                i.onSelectProduct = nt;
                i.updateView = p;
                i.onToggleCheckAll = it;
                i.onCheckChanged = tt;
                i.editProduct = ut;
                i.cancelEdit = ft;
                i.onEditSupplierSelected = et;
                i.openWarningModal = ot;
                i.onSearchKeywordInputKeyUp = st;
                i.onCreateProcurementOrder = ct;
                i.goToNewProcurementOrder = vt;
                i.onCreateProcurementApply = lt;
                i.showDetailPopover = pt;
                i.onShowDetailPopover = wt;
                i.newSearch = w;
                i.checkPriceDisabled = rt;
                yt();
                i.isRootInGroup = a.isRootGroup;
                w() })() } } }]);
supplychainModule.directive("procurementHomeView", ["$timeout", "$state", "procurementSvc", "loginContext", "eventAggregator", "tenantSvc", function(n, t, i, r, u) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/procurement/procurement-home-view.html", scope: { states: "=" }, link: function(n) { var r = function() { n.commands = [];
                    n.commands.push(new Ares.TabCommand('<i class="iconfont icon-wenhao"><\/i>帮助', f, "lc-btn lc-btn-cyan lc-btn-icon lc-btn-icon-narrow", 0)) },
                f = function() { u.publish(u.events.HelpSlideToggled, {}, "ProcurementHome") },
                t = function() { i.getProcurementSummaryHints().success(function(t) { if (t.officeProcurementApplyCount >= 0) { var i = _.find(n.states, { name: "supplychain.procurement.groupApply" });
                            i && (i.hint = t.officeProcurementApplyCount) } }) },
                e = function() { u.subscribe(n, u.events.RefreshProcurementHint, function() { t() }) };
            (function() { r();
                t();
                e() })() } } }]);
supplychainModule.directive("procurementOrderMallCartView", ["$timeout", "$q", "loginContext", "$window", "systemConfigSvc", "moduleOptionProvider", "commonSvc", function(n, t, i, r, u, f, e) { "use strict"; return { restrict: "E", templateUrl: "/app/supplychain/views/procurement/procurement-order-mall-cart-view.html", link: function(n, f) { var o = function() { f.find("#procurement-order-mall-cart-frame-container").height(angular.element(r).height() - 60);
                    n.initBasicData().then(function() { h() }) },
                s = function() { var i = t.defer(); return e.getBmsToken(n.ownerOfficeId).then(function(t) { n.universalAccessToken = t;
                        i.resolve(!0) }), i.promise },
                h = function() { t.all([s(), u.getMallHostUrl()]).then(function(t) { var i = t[1],
                            r, u;
                        i && (n.mallUrl = i, r = Date.parse(new Date), u = i + "/saasPurchase.js?v=" + r, Ares.Loader.loadJs(u, function() { c() })) }) },
                c = function() { new MallPc({ msgOrigin: n.mallUrl, containerId: "procurement-order-mall-cart-frame-container", baseUrl: n.mallUrl, token: n.universalAccessToken, permissionCodes: n.permissionCodes, userId: i.userId, tenantId: i.tenantId, officeId: i.officeId, ownerOfficeId: n.ownerOfficeId, isTenantAdmin: i.isTenantAdmin, isPurchase: !0, purchaseOrderId: n.payOrderNo, isNeedCheckPayorder: n.isNeedCheckPayorder, closeFrame: function(t) { n.close(t) } }) };
            (function() { o() })() } } }]);
supplychainModule.directive("procurementApplyOrderEditModalView", ["$window", "$log", "$timeout", "$q", "$modal", "productSvc", "enums", "aresConfirmDialog", "eventAggregator", "inventoryUtil", "aresNotification", function(n, t, i, r, u, f, e, o, s, h, c) { return { replace: !0, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-apply-order-edit-modal/procurement-apply-order-edit-modal-view.html", link: function(n, t) { var u = t.find(".table-main-content"),
                r = function() { i(function() { var t = u.find("tr:first").find("input:first");
                        t.focus();
                        angular.isFunction(t[0].select) && t[0].select();
                        n.lastInputKeyDownIsEnter = !1 }, 0, !1) },
                f = function(t, r) { var f = _.find(n.procurementApply.items, function(n) { return n.productId === t.productId }),
                        u;
                    f && !r ? o.warn({ message: "此物品已经在列表中！" }) : f && r ? f.count++ : (t.officeId = 0, u = _.extend({}, t, { count: 0, curOfficeInventoryCount: 0, rootOfficeInventoryCount: 0, orderId: n.procurementApply.id, id: 0 }), n.getProductInventoryCount(t.productId).then(function(t) { t && t.length > 0 && (u.curOfficeInventoryCount = t[0].curOfficeInventoryCount, u.rootOfficeInventoryCount = t[0].rootOfficeInventoryCount);
                        u.rootOfficeInventoryCount > 0 && !n.procurementApply.rootOfficeInventoryEnabled && (n.procurementApply.rootOfficeInventoryEnabled = !0);
                        n.procurementApply.items.unshift(u);
                        n.$modalInstance.broadcast("SKU_SELECT_ADDED", { productId: u.productId });
                        r || i(function() { n.focusNextInput() }, 0, !1) }), n.groupSalesEnabled && n.getGroupSalesPrices([u.productId]).then(function(n) { n && (u.groupSalesPrice = angular.isNumber(n[u.productId]) ? n[u.productId].toFixed(2) : "--") })) },
                e = function(t, i) { n.procurementApply.items.splice(t, 1);
                    n.$modalInstance.broadcast("SKU_SELECT_REMOVED", { productId: i.productId }) },
                h = function(n, t) { var i = n.productId || n.id;
                    s.publish(s.events.ProductSelected, i, t.delegateTarget);
                    Ares.retainOnePopover() },
                l = function(i) { var u, f; if (i) { if (i && i.keyCode !== 13) return; if (!n.lastInputKeyDownIsEnter) return;
                        u = angular.element(i.currentTarget);
                        u.hasClass("productItemSearch") ? r() : u.closest("tr").hasClass("procurement-apply-item-row") && (f = t.find(".sku-auto-complete-selector-view").find("input"), f.focus()) } else r() },
                a = function() { if (n.procurementApply.items.length === 0) return c.error("请添加采购物品"), !1; var t = _.find(n.procurementApply.items, function(n) { return !n.count }); return t ? (c.error("请输入物品【" + t.name + "】的采购数量。"), !1) : !0 },
                v = function(t, i) { a() && n.saveProcurementApply(t, i) },
                y = function(t) { t && t.originalEvent && !t.originalEvent.repeat && (n.lastInputKeyDownIsEnter = t && (t.keyCode === 13 || t.key === "Enter")) };
            (function() { n.onAddProduct = f;
                n.onRemoveProduct = e;
                n.onSelectedProduct = h;
                n.focusNextInput = l;
                n.onSave = v;
                n.onInputKeyDown = y })() } } }]);
supplychainModule.controller("ProcurementApplyOrderEditModalCtrl", ["$log", "$scope", "$modalInstance", "$q", "aresNotification", "productSvc", "loginContext", "dataHost", "inventoryUtil", "aresTreeViewUtil", "enums", "procurementApplyOrderSvc", "inventoryProductSvc", "productUnitySvc", "dataDicSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { "use strict"; var p = !1,
        k = function(n, f) { if (!p) { p = !0; var e = r.defer(); return t.procurementApply.isCommitApproval = f ? !0 : !1, t.procurementApply.status = n ? c.ProcurementApplyStatus.WaitHandle : c.ProcurementApplyStatus.Pending, l.save(t.procurementApply).then(function() { f ? u.success("审批提交成功") : n ? u.success("采购申请提交成功") : u.success("采购申请创建成功");
                    e.resolve(!0);
                    i.close(!0) }, function() { p = !1 }), e.promise } },
        d = function() { if (o.procurementApply) { if (t.procurementApply = o.procurementApply, t.groupSalesEnabled) { var n = _.pluck(t.procurementApply.items, "productId");
                    w(n).then(function(n) { n && _.each(t.procurementApply.items, function(t) { t.groupSalesPrice = angular.isNumber(n[t.productId]) ? n[t.productId].toFixed(2) : "--" }) }) } } else t.procurementApply = { id: null, rootOfficeInventoryEnabled: !1, notes: "", items: [], applyTime: moment().format("YYYY-MMM-DD HH:mm:ss"), applicantId: e.userId, applicantName: e.userName, status: c.ProcurementApplyStatus.Pending };
            t.isEdit = t.procurementApply.id > 0 },
        g = function(n) { var t = r.defer(),
                i; if (n) i = [n], a.getProductsSumCountWithRootOfficeByProductIds(i).then(function(n) { t.resolve(n.data) });
            else return null; return t.promise },
        nt = function() { i.on("SKU_SELECT_ADD", function(n) { if (n && n.data) { var i = n.data.sku; if (i) t.onAddProduct(i) } });
            i.on("TAB_SWITCHED", function() { var n = _.pluck(t.procurementApply.items, "productId");
                i.broadcast("SKU_EXIST_LIST", { productIds: n }) }) },
        tt = function() { return s.getGroupProcurementConfigs().then(function(n) { t.groupSalesEnabled = n.groupSalesEnabled }) },
        w = function(n) { var t = r.defer(); return v.getGroupSalesPrices(n).success(function(n) { t.resolve(n) }), t.promise },
        b = function() { var n = []; return n.push(y.workflowDefinitionDic.load().then(function(n) { t.procurementApplyWorkflow = _.find(n, function(n) { return n.workflowType === c.WorkflowType.ProcurementApply && !n.isDisabled == !0 }) })), r.all(n) };
    (function() { t.skuAutoCompleteOptions = { mode: "procurement", isLinkedCare: null, isOnlyEnabled: !0 };
        t.saveProcurementApply = k;
        t.getProductInventoryCount = g;
        t.getGroupSalesPrices = w;
        t.initBaseData = b;
        tt().then(function() { b().then(function() { d();
                nt() }) }) })() }]);
supplychainModule.directive("procurementInOrderAmountSettingsView", ["$timeout", "eventAggregator", function(n, t) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-in-order-amount-settings-view/procurement-in-order-amount-settings-view.html", link: function(i, r) { var u = function() { var n = r.find(".table-content"),
                        t = r.parent().height() - 147;
                    n.height(t);
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) },
                f = function(n, i) { var r = n.productId || n.id;
                    t.publish(t.events.ProductSelected, r, i.delegateTarget) },
                e = function(n, t) { var r = angular.element(t.target);
                    r.data("bs.tooltip") || r.tooltip({ placement: "top", animation: !1, html: !0, container: ".procurement-in-order-amount-settings-view", trigger: "manual", template: '<div class="tooltip tooltip-white" role="tooltip"><div class="tooltip-arrow"><\/div><div class="tooltip-inner"><\/div><\/div>', title: function() { var u = _.reduce(i.order.items, function(t, i) { return i === n ? t : t + parseFloat(i.orderCouponShare) }, 0),
                                t = (i.order.orderCouponAmount - u).toFixed(2),
                                r = '剩余可分配折扣：<span class="enyo-text-warning">￥' + t + "<\/span>",
                                f = parseFloat(n.orderCouponShare) > parseFloat(t); return f && (r += ' | <span class="enyo-text-danger"><i class="iconfont icon-chucuoshibai" style="font-size: 14px;"><\/i> 已超出<\/span>'), r } });
                    r.tooltip("show") },
                o = function(n) { angular.element(n.target).tooltip("hide") },
                s = function(n, t) { var r = angular.element(t.target);
                    r.data("bs.tooltip") || r.tooltip({ placement: "top", animation: !1, html: !0, container: ".procurement-in-order-amount-settings-view", trigger: "manual", template: '<div class="tooltip tooltip-white" role="tooltip"><div class="tooltip-arrow"><\/div><div class="tooltip-inner"><\/div><\/div>', title: function() { var u = _.reduce(i.order.items, function(t, i) { return i === n ? t : t + parseFloat(i.orderFreightShare) }, 0),
                                t = (i.order.freight - u).toFixed(2),
                                r = '剩余可运费折扣：<span class="enyo-text-warning">￥' + t + "<\/span>",
                                f = parseFloat(n.orderFreightShare) > parseFloat(t); return f && (r += ' | <span class="enyo-text-danger"><i class="iconfont icon-chucuoshibai" style="font-size: 14px;"><\/i> 已超出<\/span>'), r } });
                    r.tooltip("show") },
                h = function(n) { angular.element(n.target).tooltip("hide") },
                c = function() { i.$modalInstance.close() };
            (function() { i.close = c;
                i.onSelectProduct = f;
                i.showCouponHint = e;
                i.hideCouponHint = o;
                i.showFreightHint = s;
                i.hideFreightHint = h;
                r.find("[data-toggle=tooltip]").tooltip();
                i.init();
                n(function() { u() }, 0, !1) })() } } }]);
supplychainModule.controller("ProcurementInOrderAmountSettingsCtrl", ["$scope", "host", "$timeout", "aresNotification", "aresConfirmDialog", "$q", "procurementSvc", function(n, t, i, r, u, f, e) { "use strict"; var s = function() { var i, r;
            n.order = t.order;
            n.sensorSource = t.source;
            i = [];
            _.each(n.order.procurementOrders, function(n) { i = i.concat(n.procurementOrderItems) });
            i = _.sortBy(i, "productId");
            n.order.items = i;
            r = 0;
            _.each(n.order.items, function(n) { o(n);
                n.orderCouponShare = n.orderCouponShare.toFixed(2);
                n.orderFreightShare = n.orderFreightShare.toFixed(2);
                r += n.amount });
            n.itemAmountSum = r },
        h = function() { _.each(n.order.items, function(n) { n.orderCouponShare = n.defaultOrderCouponShare.toFixed(2);
                o(n) }) },
        c = function() { _.each(n.order.items, function(n) { n.orderCouponShare = "0.00";
                o(n) }) },
        l = function() { var t = 0;
            _.each(n.order.items, function(i, r) { n.order.orderCouponAmount ? r < n.order.items.length - 1 ? (i.orderFreightShare = i.defaultOrderCouponShare === 0 ? "0.00" : (n.order.freight * (i.defaultOrderCouponShare / n.order.orderCouponAmount)).toFixed(2), t += parseFloat(i.orderFreightShare)) : i.orderFreightShare = (n.order.freight - t).toFixed(2) : r < n.order.items.length - 1 ? (i.orderFreightShare = (n.order.freight * (i.amount / n.itemAmountSum)).toFixed(2), t += parseFloat(i.orderFreightShare)) : i.orderFreightShare = (n.order.freight - t).toFixed(2);
                o(i) }) },
        a = function() { _.each(n.order.items, function(n) { n.orderFreightShare = "0.00";
                o(n) }) },
        v = function(t, i) { o(t);
            n.showCouponHint(t, i) },
        y = function(t, i) { o(t);
            n.showFreightHint(t, i) },
        o = function(n) { n.finalAmount = n.amount - n.itemCouponAmount - parseFloat(n.orderCouponShare || 0) + parseFloat(n.orderFreightShare || 0) },
        p = function() { var e = f.defer(),
                t = 0,
                i = 0; if (_.each(n.order.items, function(n) { t += parseFloat(n.orderCouponShare);
                    i += parseFloat(n.orderFreightShare) }), t = Math.round(100 * t) / 100, i = Math.round(100 * i) / 100, t > n.order.orderCouponAmount || t < 0) r.error("折扣分摊合计不能大于￥" + n.order.orderCouponAmount.toFixed(2) + "或小于0"), e.reject();
            else if (t > 0 && t < n.order.orderCouponAmount) return u.warn({ message: "当前折扣分摊合计小于整单折扣￥" + n.order.orderCouponAmount.toFixed(2) + "，确定要保存吗？", showCancelBtn: !0 }); if (i > n.order.freight || i < 0) r.error("运费分摊合计不能大于￥" + n.order.freight.toFixed(2) + "或小于0"), e.reject();
            else if (i > 0 && i < n.order.freight) return u.warn({ message: "当前运费分摊合计小于整单运费￥" + n.order.freight.toFixed(2) + "，确定要保存吗？", showCancelBtn: !0 }); return e.resolve(), e.promise },
        w = function() { p().then(function() { var t = _.map(n.order.items, function(n) { return { procurementOrderItemId: n.id, productId: n.productId, orderFreightShare: n.orderFreightShare, orderCouponShare: n.orderCouponShare } });
                e.updateCostShareAmount(t).success(function() { r.success("保存成功");
                    n.close() }) }) };
    (function() { n.init = s;
        n.divideCouponAmount = h;
        n.clearCouponAmount = c;
        n.divideFreight = l;
        n.clearFreight = a;
        n.onOrderCouponShareChange = v;
        n.onOrderFreightShareChange = y;
        n.save = w })() }]);
supplychainModule.directive("procurementOrderDetailView", ["supplyChainPrintUtil", "procurementPayOrderUtil", "eventAggregator", "$window", "$timeout", "enums", "appNav", "aresConfirmDialog", "aresNotification", "aresModalShelf", "$modal", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-order-detail-view-dialog/procurement-order-detail-view.html", link: function(a, v) { var p = function() { var t = angular.copy(a.payOrder);
                    t.procurementOrders = a.groupAndFilterPayOrder(!0);
                    n.printProcurementOrder(t, a) },
                w = function(n) { t.viewOperationLog(n.id) },
                b = function(n, t) { var r = n.productId;
                    i.publish(i.events.ProductSelected, r, t.delegateTarget) },
                k = function(n) { var t = angular.copy(n),
                        i;
                    t.id = t.orderId;
                    i = h.open({ template: "<inventory-in-warehouse-order-list-view><\/inventory-in-warehouse-order-list-view>", controller: "inventoryInWarehouseOrderListCtrl", title: "入库信息", titleIconClass: "iconfont icon-ruku1", resolve: { dataHost: function() { return { inOrder: t } } }, needActive: !0 }) },
                d = function(n, t, i) { var r = "",
                        u = "",
                        e;
                    t.officeId = n.officeId;
                    n.isLinkedCare ? (r = "<procurement-return-order-edit-dialog-view><\/procurement-return-order-edit-dialog-view>", u = "ProcurementReturnOrderEditDialogCtrl") : (r = "<procurement-return-order-other-lc-dialog-view><\/procurement-return-order-other-lc-dialog-view>", u = "ProcurementReturnOrderOtherLcDialogCtrl", t.settlementMethod = n.settlementMethod);
                    e = c.open({ animation: !0, backdrop: "static", template: r, controller: u, windowClass: "procurement-retrun-order-dialog-wrap", resolve: { host: function() { return { payOrderItem: t, isGroupSalesOrder: n.hasGroupSalesOrder, isLinkedCare: n.isLinkedCare } } } });
                    e.result.then(function(t) { t && i && n.isLinkedCare && i.serviceOrderNo && i.status !== f.ProcurementReturnApplyStatus.Returned ? y(i) : a.loadPayOrder() }) },
                g = function(n) { var t = { action: f.ProcurementMallAction.OrderDetail, orderSn: n.orderNo, lcCode: n.barCode };
                    e.goToState("mallCenter", t) },
                nt = function(n) { var t = { action: f.ProcurementMallAction.OrderDetail, orderSn: n.orderNo };
                    e.goToState("mallCenter", t) },
                y = function(n) { var t = { action: f.ProcurementMallAction.ServiceOrder, serviceSn: n.serviceOrderNo };
                    e.goToState("mallCenter", t) },
                tt = function() { o.confirm({ message: "确定作废当前采购订单？" }).then(function() { a.cancelPayOrder().then(function(n) { n ? (s.success("操作成功"), a.$modalInstance.close(!0)) : s.error("操作失败") }, function(n) { n && (n.name == "InventoryOperationException" || n.name == "AresBusinessException") ? s.error(n.message) : s.error("操作失败!") }) }) },
                it = function() { var i = a.payOrder,
                        n = angular.copy(i),
                        t = angular.copy(n.procurementOrders[0]);
                    n.id = null;
                    n.status = 0;
                    n.payOrderNo = null;
                    n.platformTradeNo = null;
                    n.isSyncToDealer = !0;
                    n.orderDate = moment().format("YYYY-MM-DD");
                    n.checkStatus = 0;
                    n.checkTime = null;
                    n.checkUserId = null;
                    n.checkUserName = null;
                    n.recordCreatedTime = null;
                    n.recordCreatedUser = 0;
                    n.purchaserId = l.providerId > 0 ? l.providerId : 0;
                    n.purchaserName = null;
                    i.isLinkedCare && (n.freight = 0, n.couponAmount = 0, t.freight = 0, t.couponAmount = 0);
                    t.id = null;
                    t.status = 0;
                    t.type = 0;
                    t.payOrderId = null;
                    t.orderNo = null;
                    t.payOrderNo = null;
                    t.procurementOrderItems = [];
                    _.each(i.procurementOrders, function(n) { _.each(n.procurementOrderItems, function(n) { n.producer = n.producter;
                            i.isLinkedCare && (n.itemCouponAmount = 0);
                            t.procurementOrderItems.push(n) }) });
                    n.procurementOrders = [t];
                    a.$modalInstance.close({ furtherAction: "copy", newPayOrder: n }) },
                rt = function() { a.$modalInstance.close({ furtherAction: "edit", payOrderId: a.payOrder.id }) },
                ut = function() { a.$modalInstance.close({ furtherAction: "commit", payOrder: a.payOrder }) },
                ft = function() { var n = v.find(".procurement-order-detail-body");
                    n.height(angular.element(r).height() - 222);
                    n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) },
                et = function() { var n = h.open({ title: "入库金额设置", template: "<procurement-in-order-amount-settings-view><\/procurement-in-order-amount-settings-view>", controller: "ProcurementInOrderAmountSettingsCtrl", resolve: { host: function() { return { order: angular.copy(a.payOrder), source: "ProcurementOrder" } } }, needActive: !0 });
                    n.result.then(function() { a.loadPayOrder() }) };
            (function() { a.isGroup = l.isGroup;
                a.printPayOrder = p;
                a.viewOperationLog = w;
                a.onSelectProduct = b;
                a.showInOrderDetail = k;
                a.onCreateReturnOrder = d;
                a.onCreateReturnOrderApply = g;
                a.onCancelProcurementOrder = tt;
                a.onCopyProcurementOrder = it;
                a.onEditProcurementOrder = rt;
                a.goToMallOrderDetail = nt;
                a.goToMallServiceDetail = y;
                a.onCommitPayOrder = ut;
                a.showAmountSettingsModal = et;
                a.officeId = l.officeId;
                a.initBaseData().then(function() { a.loadPayOrder().then(function() { u(function() { ft() }, 0, !1) }) }) })() } } }]);
supplychainModule.controller("ProcurementOrderDetailCtrl", ["host", "$scope", "procurementSvc", "inventoryUtil", "enums", "loginContext", "permissionProvider", "procurementPayOrderUtil", "$q", "dataDicSvc", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var rt = function(n) { if (t.disableAction || n.createdOfficeId !== f.officeId || n.hasReturnOrder || n.isLinkedCare && n.status != u.ProcurementPayOrderStatus.PreCommit || n.checkStatus != u.ProcurementPayOrderCheckStatus.NoNeed && n.checkStatus != u.ProcurementPayOrderCheckStatus.PreSubmit || n.status == u.ProcurementPayOrderStatus.InStorage || n.status == u.ProcurementPayOrderStatus.PartInStorage || n.status == u.ProcurementPayOrderStatus.Canceled) return !1; var i = _.find(n.settlementItems, function(n) { return n.orderType === u.ProcurementSettlementOrderType.ProcurementSettlementOrder }); return i ? !1 : !0 },
        v = function(n) { var i, r; return t.disableAction ? !1 : n.createdOfficeId !== f.officeId || n.hasReturnOrder ? !1 : (i = _.some(n.settlementItems, function(n) { return n.status !== u.ProcurementSettleItemStatus.Settled }), i) ? !1 : (r = n.isCanUpdateOrder, r && n.isCanUpdateItem !== !1 || !n.isLinkedCare && (n.checkStatus == u.ProcurementPayOrderCheckStatus.Rejected || n.checkStatus == u.ProcurementPayOrderCheckStatus.Checked)) },
        y = function(n) { return t.disableAction ? !1 : t.groupSalesEnabled && n.officeId !== f.officeId ? !1 : n.createdOfficeId === f.officeId },
        p = function(n) { return t.disableAction ? !1 : e.isAllowed("inventoryOperation.stockInBrowser") && n.officeId === f.officeId && (n.status === 1 || n.status === 2) && (n.checkStatus == u.ProcurementPayOrderCheckStatus.NoNeed || n.checkStatus == u.ProcurementPayOrderCheckStatus.Checked) },
        w = function(n) { return (n.hasGroupSalesOrder || !n.hasGroupSalesOrder && n.createdOfficeId === f.officeId) && n.status != u.ProcurementPayOrderStatus.Committing && n.status != u.ProcurementPayOrderStatus.Pending && n.status != u.ProcurementPayOrderStatus.Canceled && (n.checkStatus == u.ProcurementPayOrderCheckStatus.Checked || n.checkStatus == u.ProcurementPayOrderCheckStatus.NoNeed) },
        c = function(n) { var i = angular.copy(l); return _.each(i, function(i) { n || (i.procurementOrderItems = _.filter(i.procurementOrderItems, function(n) { return !t.skuSearchKeyword || n.productName.indexOf(t.skuSearchKeyword) > -1 }));
                _.each(i.procurementOrderItems, function(n) { n.delivered = n.status === u.ProcurementOrderItemDeliveredStatus.Delivered || n.status === u.ProcurementOrderItemDeliveredStatus.PartDelivered }); var r = _.groupBy(i.procurementOrderItems, "delivered");
                i.deliveredItems = r["true"];
                i.undeliveredItems = r["false"];
                i.expanded = !0;
                i.deliveredItemsExpanded = !0;
                i.undeliveredItemsExpanded = !0 }), i },
        l, b = function() { return i.getPayOrderFullById(t.payOrderId).success(function(n) { n.isLinkedCare = n.type === u.ProcurementOrderType.LinkedCare;
                l = angular.copy(n.procurementOrders);
                n.procurementOrders = c();
                n.canEdit = !t.disableAction && n.isCanUpdateOrder;
                n.canCancel = v(n);
                n.canCopy = y(n);
                n.canInOrder = p(n);
                n.canReturn = w(n);
                n.canCommit = n.createdOfficeId === f.officeId && n.status === u.ProcurementPayOrderStatus.PreCommit;
                n.canSetCouponFreight = n.status === u.ProcurementPayOrderStatus.PreInStorage && (n.orderCouponAmount > 0 || n.freight > 0) && (n.checkStatus === u.ProcurementPayOrderCheckStatus.Checked || n.checkStatus === u.ProcurementPayOrderCheckStatus.NoNeed) && moment(n.recordCreatedTime).isAfter("2019-03-01");
                n.statusLabel = o.getStatusLabelHtml(n); var i = _.find(t.offices, function(t) { return t.id === n.officeId });
                n.officeName = i.abbreviation;
                _.each(n.procurementOrders, function(t) { t.canGoToMallDetal = n.isLinkedCare && t.status !== u.ProcurementPayOrderStatus.PreCommit && t.orderNo;
                    a(n, t.undeliveredItems);
                    a(n, t.deliveredItems) });
                n.isSettled = n.status === u.ProcurementPayOrderStatus.Pending || n.status === u.ProcurementPayOrderStatus.PreCommit || n.status === u.ProcurementPayOrderStatus.Committing || n.checkStatus === u.ProcurementPayOrderCheckStatus.Pending || n.checkStatus === u.ProcurementPayOrderCheckStatus.PreSubmit || n.checkStatus === u.ProcurementPayOrderCheckStatus.Rejected ? !1 : n.paymentAmount === n.actualAmount;
                t.payOrder = n;
                t.showOtherInfo = n.notes || n.inorders && n.inorders.length > 0 || n.settlementItems && n.settlementItems.length > 0 }) },
        a = function(n, t) { _.each(t, function(t) { _.each(t.returnOrderItems, function(t) { t.canCreateReturn = !t.isAlreadyHandler && (t.status === u.ProcurementReturnApplyStatus.Approved || t.status === u.ProcurementReturnApplyStatus.Handled || t.status === u.ProcurementReturnApplyStatus.Returned) && n.createdOfficeId === f.officeId;
                    t.statusStr = t.status === u.ProcurementReturnApplyStatus.Returned && t.canCreateReturn ? "已退款" : "退货已通过" }) }) },
        k = function() { r.getProductCodeOptions().then(function(n) { t.allowInsideCode = n.allowInsideCode }) },
        d = function(n) { o.goToInOrder(n) },
        g = function() { var n = s.defer(); return i.cancelPayOrder(t.payOrder.id).success(function(t) { n.resolve(t) }).error(function(t) { n.reject(t) }), n.promise },
        nt = function(n) { n && (t.skuSearchKeyword = "");
            t.payOrder.procurementOrders = c() },
        tt = function() { return h.officeDic.load().then(function(n) { t.offices = n }) },
        it = function(n) { var i = _.clone(n);
            i.items = [];
            i.orderDateStr = moment(i.orderDate).format("YYYY-MM-DD");
            _.each(i.procurementOrders, function(n) { _.each(n.procurementOrderItems, function(n) { i.items.push({ name: n.name, code: n.code, producer: n.producer, specification: n.specification, unit: n.unit, price: n.price, number: n.number, amount: n.amount, notes: n.notes }) }) });
            i.showSettlementInfo = i.status === u.ProcurementPayOrderStatus.Pending || i.status === u.ProcurementPayOrderStatus.PreCommit || i.status === u.ProcurementPayOrderStatus.Committing || i.checkStatus === u.ProcurementPayOrderCheckStatus.Pending || i.checkStatus === u.ProcurementPayOrderCheckStatus.PreSubmit || i.checkStatus === u.ProcurementPayOrderCheckStatus.Rejected ? !1 : !0;
            o.exportExcel(i, { allowInsideCode: t.allowInsideCode }) };
    (function() { t.skuSearchKeyword = "";
        t.disableAction = n.disableAction;
        t.payOrderId = n.payOrderId;
        t.groupSalesEnabled = n.groupSalesEnabled;
        t.initBaseData = tt;
        t.loadPayOrder = b;
        t.returnStatusEnums = u.ProcurementReturnApplyStatus;
        t.goToInOrder = d;
        t.cancelPayOrder = g;
        t.searchSku = nt;
        t.groupAndFilterPayOrder = c;
        t.exportExcel = it;
        k() })() }]);
supplychainModule.directive("procurementOrderEditModalView", ["$window", "$log", "$timeout", "$q", "$modal", "productSvc", "enums", "aresConfirmDialog", "eventAggregator", "inventoryUtil", "aresNotification", "productUtil", "aresAccordionUtil", "dataDicSvc", "lcUploadUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { return { replace: !0, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-order-edit-modal/procurement-order-edit-modal-view.html", link: function(n, t) { var wt = function(n) { if (n === null || n === undefined || n === "" || isNaN(n)) return null; var t = parseInt(n); return t > 0 ? t : 0 },
                d = function(n, t) { p(n, t) },
                g = function(n, t) { p(n, t) },
                nt = function(n) { if (n.number > 0) { var t = (parseFloat(n.amount) / parseInt(n.number)).toFixed(2);
                        t === "NaN" && (t = "0.00");
                        n.price = t } r() },
                p = function(n) { if (n.price !== null && n.number !== null) { var t = (parseFloat(n.price) * parseInt(n.number)).toFixed(2);
                        t === "NaN" && (t = "0.00");
                        n.amount = t } r() },
                r = function() { var t = 0;
                    angular.forEach(n.payOrderList, function(i) { var r = i.procurementOrders[0],
                            f = 0,
                            u;
                        angular.forEach(r.procurementOrderItems, function(t) { f += parseFloat(t.amount);
                            n.itemCountMap = n.itemCountMap || {};
                            n.itemCountMap[t.productId] = n.itemCountMap[t.productId] || {};
                            n.itemCountMap[t.productId][t.dealerId || i.supplierId] = t.number });
                        f = parseFloat(f.toFixed(2));
                        r.totalAmount = f;
                        u = f;
                        parseFloat(r.couponAmount) > 0 && (u -= Ares.priceToFixed(r.couponAmount));
                        parseFloat(r.freight) > 0 && (u += Ares.priceToFixed(r.freight));
                        u = parseFloat(u.toFixed(2));
                        r.paymentAmount = u;
                        t += u;
                        r.totalNum = r.procurementOrderItems.length;
                        i.couponAmount = r.couponAmount;
                        i.freight = r.freight;
                        i.paymentAmount = r.paymentAmount;
                        i.totalAmount = r.totalAmount;
                        n.isEdit || i.supplierType !== e.OrganizationType.NormalDealer || (r.actualAmount = i.settlementMethod === e.SettlementMethod.Instantly ? u : 0, i.actualAmount = r.actualAmount);
                        n.isGroupSalesPayOrder && (r.actualAmount = u, i.actualAmount = r.actualAmount);
                        i.actualAmount = (parseFloat(i.actualAmount) || 0).toFixed(2) });
                    n.paymentAmount = parseFloat(t.toFixed(2)) },
                tt = function(n, t) { var i = n.productId || n.id;
                    s.publish(s.events.ProductSelected, i, t.delegateTarget);
                    Ares.retainOnePopover() },
                it = function() { var r, s, u, f, t, o, i; return n.orderDate ? !n.selectedPurchaser || !n.selectedPurchaser.id ? (c.error("请选择采购人。"), !1) : n.isEdit && !n.isGroupSalesPayOrder && !n.editSupplier.id ? (c.error("请选择供应商。"), !1) : (r = !1, angular.forEach(n.payOrderList, function(n) { var t = n.procurementOrders[0].procurementOrderItems;
                        angular.forEach(t, function(n) { n.number || (r = !0, s = n) }) }), r) ? (c.error("请输入物品【" + s.name + "】的采购数量。"), !1) : n.payOrderList && n.payOrderList.length === 1 && n.payOrderList[0].supplier === "无供应商" ? (c.error("请选择供应商"), !1) : !n.procurementPayOrderProductItems || !n.procurementPayOrderProductItems.length ? (c.error("请添加物品"), !1) : (u = _.find(n.payOrderList, function(n) { return parseFloat(n.paymentAmount) < 0 }), u) ? (t = "折扣金额不能大于物品总额", n.isEdit || n.isGroupSalesPayOrder || (t = "供应商【" + u.supplier + "】的采购单" + t), c.error(t), !1) : (f = _.find(n.payOrderList, function(n) { return parseFloat(n.actualAmount) > parseFloat(n.paymentAmount) }), f) ? (t = "实付金额不能大于应付金额", n.isEdit || (t = "供应商【" + f.supplier + "】的采购单" + t), c.error(t), !1) : n.isNeedCheckAgreePrice && (i = !1, angular.forEach(n.payOrderList, function(n) { var t = n.procurementOrders[0].procurementOrderItems;
                        angular.forEach(t, function(t) { if (typeof t.isNotAgreedProduct == "undefined") { var r = _.find(t.dealers, function(t) { return t.dealerId == n.supplierId });
                                r && r.dealerType != e.OrganizationType.NormalDealer && r.isNotAgreedProduct && (o = t.name, i = !0) } else t.isNotAgreedProduct && t.dealerType != e.OrganizationType.NormalDealer && (o = t.name, i = !0) }) }), i) ? (c.error("该物品【" + o + "】为非协议商品，无法去商城采购"), !1) : !0 : (c.error("请选择单据日期。"), !1) },
                rt = function() { n.source === e.ProcurementPayOrderSource.PurchaseApply ? o.confirm({ message: "暂存操作会将当前采购申请转成未确认的采购单，确定暂存吗？" }).then(function() { f(!0) }) : f(!0) },
                f = function(t) { if (Ares.ensureNotDuplicated("ProcurementOrderSaveCheck") && it()) { n.formatPayOrderList(t); var i = !1,
                            r;
                        angular.forEach(n.payOrderList, function(n, t) { n.supplier === "无供应商" && (i = !0, r = t) });
                        i ? o.confirm({ message: "还有物品未指定供应商，确定下单吗？" }).then(function() { n.payOrderList.splice(r, 1);
                            w(t) }) : w(t) } },
                w = function(t) { n.saveProcurementOrder(t).then(function(t) { var r = n.isEdit ? "保存成功" : n.payOrderList.length === 1 ? "下单成功" : "合并下单成功，请于采购订单页面查询",
                            i;
                        c.success(r);
                        v.dealerDic.refresh();
                        n.$modalInstance.close(t);
                        i = n.isEdit && n.payOrderList[0].status != 5 ? "保存" : "直接下单";
                        Ares.sensors.track("ProcurementOrderEditModalCtrl", { PatientName: n.payOrderList[0].notes, OperationType: i }) }, function(n) { var t;
                        (n.name === "ArgumentException" || n.name === "InventoryOperationException") && (t = n.message);
                        c.error(t || "操作失败") }) },
                bt = function(t) { angular.forEach(n.payOrderList, function(n) { t.isPushOrder = n.supplierType != e.OrganizationType.NormalDealer;
                        _.extend(n, t) }) },
                ut = function() { var i = n.payOrderList; return { element: t, data: i, secondDatakey: "procurementOrderItems", containerElement: "#tabs", tabElement: ".accordion-tab", rowHeight: 40, tabHeight: 24, scrollbarWidth: 10, parentTopOffset: 50 } },
                h, u = function() { i(function() { var n = ut();
                        h = new a.AresAccordion(n);
                        h.init() }) },
                ft = function(n) { h.triggerTab(n) },
                b = function(t, i, f) { var s, l, h, a, o, v, y, p; if (i.dealerName != t.dealerName || !angular.isDefined(f)) { if (n.isNeedCheckAgreePrice && i.dealerType != e.OrganizationType.NormalDealer && i.isNotAgreedProduct) { c.error("该物品【" + t.name + "】为非协议商品，无法去商城采购"); return } s = { dealerId: i.dealerId, dealerName: i.dealerName, dealerType: i.dealerType, dealerCode: i.dealerCode, price: (i.price || 0).toFixed(2), settlementMethod: i.settlementMethod };
                        angular.isDefined(f) ? (l = n.payOrderList[f].procurementOrders[0].procurementOrderItems, l = _.filter(l, function(n) { return n.productId != t.productId }), n.payOrderList[f].procurementOrders[0].procurementOrderItems = l, n.itemCountMap[t.productId][t.dealerId] = 0) : (s.number = i.count, n.itemCountMap[t.productId][i.dealerId] = i.count, h = _.find(n.payOrderList, function(n) { return n.supplierId == i.dealerId }), h && (a = _.find(h.procurementOrders[0].procurementOrderItems, function(n) { return n.productId === t.productId }), a && (s.price = a.price, s.notes = a.notes), h.procurementOrders[0].procurementOrderItems = _.filter(h.procurementOrders[0].procurementOrderItems, function(n) { return n.productId != t.productId })));
                        (angular.isDefined(f) || s.number) && (o = angular.copy(t), _.extend(o, s), angular.isUndefined(s.notes) && (o.notes = ""), o.amount = (parseFloat(o.price) * parseInt(o.number)).toFixed(2), v = !1, angular.forEach(n.payOrderList, function(t, i) { if (o.dealerName == t.supplier) { var r = n.payOrderList[i].procurementOrders[0],
                                    u = _.find(r.procurementOrderItems, function(n) { return n.productId == o.productId });
                                u ? u.number += o.number : r.procurementOrderItems.push(o);
                                v = !0 } }), v || (y = { supplier: o.dealerName, supplierId: o.dealerId, supplierType: o.dealerType, supplierCode: o.dealerCode, procurementOrders: [], settlementMethod: s.settlementMethod }, p = { totalNum: 0, totalAmount: 0, paymentAmount: 0, freight: 0, couponAmount: 0, procurementOrderItems: [o] }, y.procurementOrders.push(p), n.payOrderList.push(y)));
                        k();
                        r();
                        n.payOrderListSort();
                        u() } },
                et = function(n, t) { var i = _.values(t);
                    i.push({ 0: 0 });
                    _.each(i, function(t) { b(n, t) }) },
                ot = function(t, i, f) { var e, o;
                    f.id && (e = t.procurementOrders[0].procurementOrderItems, angular.forEach(e, function(n) { n.dealerId = f.id;
                        n.dealerName = f.name;
                        n.dealerType = f.type }), n.payOrderList.splice(i, 1), o = !1, angular.forEach(n.payOrderList, function(t, i) { if (f.name == t.supplier) { var r = t.procurementOrders[0],
                                u = r.procurementOrderItems,
                                s = n.payOrderList[i].procurementOrders[0];
                            s.procurementOrderItems = u.concat(e);
                            o = !0 } }), o || (t.supplier = f.name, t.supplierId = f.id, t.supplierCode = f.code, t.supplierType = f.type, n.payOrderList.push(t)), r(), n.payOrderListSort(), u()) },
                st = function(t, i, f) { o.confirm({ message: "确认要删除该物品？" }).then(function() { var e = 0,
                            o;
                        _.each(n.payOrderList, function(n) { var i = _.find(n.procurementOrders[0].procurementOrderItems, function(n) { return n.productId === t.productId });
                            i && e++ });
                        i.splice(f, 1);
                        e > 0 && (o = _.findIndex(n.procurementPayOrderProductItems, function(n) { return n.productId === t.productId && n.dealerId === t.dealerId }), n.procurementPayOrderProductItems.splice(o, 1), n.$modalInstance.broadcast("SKU_SELECT_REMOVED", { productId: t.productId }));
                        n.itemCountMap[t.productId][t.dealerId] = 0;
                        k();
                        r();
                        n.payOrderListSort();
                        u() }) },
                k = function() { n.isEdit || n.isGroupSalesPayOrder || angular.forEach(n.payOrderList, function(t, i) { var r = t.procurementOrders[0];
                        r.procurementOrderItems.length || n.payOrderList.splice(i, 1) }) },
                ht = function() { if (!n.isNeedCheckAgreePrice) return !0; var t = _.find(n.procurementPayOrderProductItems, function(t) { var i = _.find(t.dealers, function(t) { return t.dealerName === n.editSupplier.name }); return i && i.isNotAgreedProduct && i.dealerType != e.OrganizationType.NormalDealer }); return t ? (n.editSupplier = n.lastSupplier ? angular.copy(n.lastSupplier) : { id: 0, name: "选择供应商" }, c.error("该物品【" + t.name + "】为非协议商品，无法去商城采购"), !1) : !0 },
                ct = function(t) { var r = function() { var t, i;
                            n.lastSupplier = angular.copy(n.editSupplier);
                            n.confirmUpdateProductPrices();
                            t = n.editSupplier.type != e.OrganizationType.NormalDealer;
                            n.skuAutoCompleteOptions.isLinkedCare = t;
                            n.payOrderList[0].supplier = n.editSupplier.name;
                            n.payOrderList[0].supplierId = n.editSupplier.id;
                            n.payOrderList[0].supplierCode = n.editSupplier.code;
                            n.payOrderList[0].supplierType = n.editSupplier.type;
                            n.payOrderList[0].procurementOrders[0].freight = 0;
                            n.payOrderList[0].procurementOrders[0].couponAmount = 0;
                            n.$modalInstance.broadcast("SUPPLIER_SELECTED", { isLinkedCare: t, dealerId: n.editSupplier.id });
                            i = _.pluck(n.procurementPayOrderProductItems, "productId");
                            n.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: i }) },
                        u = n.payOrderList[0].procurementOrders[0],
                        f;
                    n.editSupplier.type != e.OrganizationType.NormalDealer ? (f = _.some(u.procurementOrderItems, function(n) { return !l.isLinkedCareProduct(n.barCode) }), f ? o.confirm({ message: "系统将自动清除e看牙商城中没有的物品，是否继续？" }).then(function() { u.procurementOrderItems = _.filter(u.procurementOrderItems, function(n) { return l.isLinkedCareProduct(n.barCode) });
                        n.procurementPayOrderProductItems = _.filter(n.procurementPayOrderProductItems, function(n) { return l.isLinkedCareProduct(n.barCode) });
                        n.lastSupplier = angular.copy(n.editSupplier);
                        r() }, function() { i(function() { n.editSupplier = n.lastSupplier ? angular.copy(n.lastSupplier) : { id: 0, name: "选择供应商" } }) }) : ht(t) && r()) : r() },
                lt = function(t) { n.selectedOfficeIdsArray = _.pluck(t, "officeId");
                    n.groupSalesEnabled && (n.isGroupSalesPayOrder = n.selectedOfficeIdsArray[0] !== n.createdOfficeId, n.isEdit ? n.payOrderList[0].procurementOrders[0].procurementOrderItems = [] : n.isGroupSalesPayOrder ? n.createGroupSalesPayOrder() : n.payOrderList = [], n.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: [] }), n.procurementPayOrderProductItems = [], n.isGroupSalesPayOrder && n.kendoControls.dealerDropDownList && (n.kendoControls.dealerDropDownList.destroy(), n.kendoControls.dealerDropDownList.wrapper.remove()), n.checkShowSyncDealer()) },
                at = function(i, r) { var u, f, e; if (r) u = t.find(".table-main-content").find('tr[data-product-id="' + r + '"]').find("input:first"), u.focus(), angular.isFunction(u[0].select) && (u[0].select(), n.lastInputKeyDownIsEnter = !1);
                    else { if (i && i.keyCode !== 13) return; if (!n.lastInputKeyDownIsEnter) return;
                        f = angular.element(i.target);
                        u = f.closest("td").next().find("input.ares-numeric-input-input");
                        u.length === 1 ? (u.focus(), n.lastInputKeyDownIsEnter && angular.isFunction(u[0].select) && (u[0].select(), n.lastInputKeyDownIsEnter = !1)) : (e = t.find(".sku-auto-complete-selector-view").find("input"), e.focus()) } },
                vt = function(t) { t && t.originalEvent && !t.originalEvent.repeat && (n.lastInputKeyDownIsEnter = t && (t.keyCode === 13 || t.key === "Enter")) },
                yt = function() { i(function() { t.find('[data-toggle="tooltip"]').tooltip() }, 0, !1) },
                pt = function() { var r = t.find("#purchase-product-import"),
                        i = new y.UploadUtil({ url: "api/v1/procurement-payorder/purchase-products/parse-excel", acceptFileTypes: /(\.|\/)(xls|xlsx)$/i }, r);
                    i.register(y.eventNames.done, function(t, i) { i.result && (i.result.transMessage && o.warn({ message: i.result.transMessage }), i.result.successItems && n.addBatchProducts(i.result.successItems)) });
                    y.popUploadInfo(i);
                    t.find("#upload-button").on("click", function() { n.procurementPayOrderProductItems && n.procurementPayOrderProductItems.length > 0 ? o.confirm({ message: "当前物品明细将被清空，确认导入吗？" }).then(function() { t.find("#purchase-product-import").click() }) : t.find("#purchase-product-import").click() }) };
            (function() { n.kendoDatePickerOptions = { format: "yyyy-MM-dd" };
                n.onRemoveProduct = st;
                n.onSelectedProduct = tt;
                n.onItemNumberChange = d;
                n.onItemPriceChange = g;
                n.onItemAmountChange = nt;
                n.onSave = f;
                n.onSaveOnly = rt;
                n.initAccordionTab = u;
                n.tabScrollTo = ft;
                n.onDealerChange = ot;
                n.switchSuplier = b;
                n.calcOrderPayAmount = r;
                n.onEditSupplierChange = ct;
                n.onOfficeSelected = lt;
                n.focusNextInput = at;
                n.refreshTooltip = yt;
                n.onInputKeyDown = vt;
                n.onDealerCountChange = et;
                n.rightHasSpu = !1;
                n.hasSupplier = !1;
                n.kendoControls = { dealerDropDownList: null };
                pt();
                n.init() })() } } }]);
supplychainModule.controller("ProcurementOrderEditModalCtrl", ["$log", "$scope", "$modalInstance", "$q", "$modal", "aresNotification", "productSvc", "systemitemSvc", "aresConfirmDialog", "practiceSvc", "dataDicSvc", "loginContext", "procurementSvc", "dataHost", "enums", "officeSelectorUtil", "officeSvc", "workflowSvc", "productUtil", "$timeout", "inventoryUtil", "officeUtil", "productUnitySvc", "inventoryProductSvc", "officeOptionSvc", "permissionProvider", "moduleOptionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt, ut, ft) { "use strict"; var wt = function() { return g.getGroupProcurementConfigs().then(function(n) { return t.groupSalesEnabled = n.groupSalesEnabled, t.isShowOfficeSelector = l.isGroup && l.isRootGroup && !v.applyOrderParams, t.currentOfficeName = nt.getAbbreviation(l.officeId), t.isGroupSalesPayOrder = !1, !0 }) },
        oi = function() { return rt.getOfficeOption(rt.optionKeys.IsProcurementPriceLockEnabled).then(function(n) { t.isProcurementPriceLockEnabled = n }) },
        bt = function() { var i = r.defer(),
                n; return t.orderDate = moment(Ares.today()).format("YYYY-MM-DD"), n = [], n.push(c.currentOfficeWorkProviderDic.load().then(function(n) { n = _.filter(n, function(n) { return !n.isInactive && n.isShow !== !1 });
                n.unshift({ id: 0, name: "选择采购人" });
                t.usersSource = n; var i = l.providerId;
                t.selectedPurchaser = { id: i > 0 ? i : 0, name: l.userName } })), n.push(c.officeDic.load().then(function(n) { t.offices = n })), t.groupSalesEnabled && v.applyOrderParams || (n.push(c.dealerDic.loadActive().then(function(n) { t.dealersSource = [{ id: 0, name: "选择供应商" }].concat(n);
                t.dealersSourceWithoutLc = [{ id: 0, name: "一键设置供应商" }].concat(_.filter(n, function(n) { return n.type === y.OrganizationType.NormalDealer }));
                t.selectedSupplier = { id: 0, type: y.OrganizationType.NormalDealer } })), t.isShowOfficeSelector && n.push(w.getSelfAndChildOfficesByGroupId(l.officeId, !1).success(function(n) { t.officeTreeData = p.setId(n);
                t.officeTreeData && t.officeTreeData.length > 0 && angular.forEach(t.officeTreeData, function(n) { angular.forEach(n.items, function(n) {
                        (n.hasChildren && n.isGroup || n.bizType == 0) && (n.disabled = !0);
                        n.items && n.items.length > 0 && angular.forEach(n.items, function(n) {
                            (n.hasChildren && n.isGroup || n.bizType == 0) && (n.disabled = !0);
                            n.items && n.items.length > 0 && angular.forEach(n.items, function(n) {
                                (n.hasChildren && n.isGroup || n.bizType == 0) && (n.disabled = !0) }) }) }) });
                t.selectMode = ft.isGroupInventoryEnabled() ? "all" : "officeOnly" }))), n.push(nt.isRootGroup().then(function(n) { t.canCreateSpu = n && ut.isAllowed("product.productInfo") })), n.push(g.checkCanEditProcurementPrice().then(function(n) { t.canEditProcurementPrice = n })), n.push(rt.getOfficeOption(rt.optionKeys.IsNeedCheckAgreePrice).then(function(n) { t.isNeedCheckAgreePrice = n })), r.all(n).then(function() { i.resolve(!0) }), i.promise },
        et = function(n) { var i = r.defer(),
                u = _.pluck(t.procurementPayOrderProductItems, "productId"),
                f = { productIds: u, isOnlyDefaultDealer: !!n }; return e.getProductDealersByProductIds(f).success(function(n) { i.resolve(n) }), i.promise },
        kt = function(n) { var t = r.defer(); if (n.dealers) t.resolve(!0);
            else return e.getProductDealersByProductIds({ productIds: [n.productId] }).success(function(i) { n.dealers = i;
                t.resolve(!0) }); return t.promise },
        st = function(n) { var i = _.groupBy(n, "productId");
            angular.forEach(t.procurementPayOrderProductItems, function(n) { var r = { dealerId: 0, dealerName: "无供应商", dealerType: y.OrganizationType.NormalDealer, price: 0 },
                    u = i[n.productId] || [],
                    t = _.find(u, function(n) { return n.isPreferred });
                t && t.price > 0 && (r.dealerId = t.dealerId, r.dealerCode = t.dealerCode, r.dealerName = t.dealerName, r.dealerType = t.dealerType, r.isNotAgreedProduct = t.isNotAgreedProduct, r.price = t.price, r.settlementMethod = t.settlementMethod);
                _.extend(n, r);
                n.amount = (parseFloat(n.price) * parseInt(n.number)).toFixed(2) }) },
        ht = function() { var n = _.groupBy(t.procurementPayOrderProductItems, "dealerId"),
                r = _.keys(n),
                i = [];
            angular.forEach(r, function(t) { var e = n[t],
                    u = e[0],
                    f = { supplier: u.dealerName, supplierType: u.dealerType, supplierId: u.dealerId || null, supplierCode: u.dealerCode || null, procurementOrders: [] },
                    r = { totalNum: 0, totalAmount: 0, actualAmount: 0, paymentAmount: 0, freight: 0, couponAmount: 0, procurementOrderItems: [] };
                angular.forEach(e, function(n) { r.totalAmount += n.price * n.number;
                    r.procurementOrderItems.push(n) });
                r.totalNum = r.procurementOrderItems.length;
                t > 0 && (f.settlementMethod = r.procurementOrderItems[0].settlementMethod);
                f.procurementOrders.push(r);
                i.push(f) });
            t.payOrderList = i;
            ct() },
        ot = function() { var n = { supplier: t.currentOfficeName, supplierType: y.OrganizationType.NormalDealer, procurementOrders: [] };
            n.procurementOrders.push({ totalNum: 0, totalAmount: 0, actualAmount: 0, paymentAmount: 0, freight: 0, couponAmount: 0, procurementOrderItems: [] });
            t.payOrderList = [n] },
        ct = function() { lt();
            t.calcOrderPayAmount();
            t.initAccordionTab();
            t.refreshTooltip() },
        lt = function() { var n = angular.copy(t.payOrderList),
                i = _.filter(n, function(n) { return n.supplierType != y.OrganizationType.NormalDealer }),
                r = _.filter(n, function(n) { return n.supplier === "无供应商" }),
                u = _.filter(n, function(n) { return n.supplier !== "无供应商" && n.supplierType === y.OrganizationType.NormalDealer }),
                f = i.concat(u).concat(r);
            t.payOrderList = f },
        dt = function(n) { var i = r.defer(); return t.isEdit ? (t.isGroupSalesPayOrder || (t.payOrderList[0].supplier = t.editSupplier.name), a.updateProcurementPayOrder(t.payOrderList[0]).success(function(t) { n || t.checkStatus !== y.ProcurementPayOrderCheckStatus.PreSubmit ? i.resolve(t) : s.confirm({ message: "该订单需要审批，是否提交审批？您也可以暂时保存该订单，稍后再提交。", confirmText: "提交审批", cancelText: "保存" }).then(function() { b.startProcurementPayOrderWorkflow(t.id).success(function() { f.success("已成功提交审批");
                        i.resolve(!0) }) }, function() { i.resolve(!0) }) }).error(function(n) { i.reject(n) })) : a.createPayOrderBatch(t.payOrderList).success(function(n) { i.resolve(n) }).error(function(n) { i.reject(n) }), i.promise },
        si = function() { var n = !1; return t.selectedSupplier && t.selectedSupplier.type != y.OrganizationType.NormalDealer && (n = !0), n },
        at = function() { return t.editSupplier && t.editSupplier.type != y.OrganizationType.NormalDealer },
        gt = function() { var r, i, n;
            t.procurementPayOrderProductItems = v.procurementPayOrderProductItems || [];
            t.applyOrderParams = v.applyOrderParams;
            t.source = v.source;
            t.isNewAdd = v.isNewAdd;
            v.procurementPayOrder ? (t.isEdit = !!v.procurementPayOrder.id, t.payOrderList = [v.procurementPayOrder], _.each(v.procurementPayOrder.procurementOrders[0].procurementOrderItems, function(n) { n.price = (n.price || 0).toFixed(2);
                t.procurementPayOrderProductItems.push(n) }), t.orderDate = moment(v.procurementPayOrder.orderDate).format("YYYY-MM-DD"), t.selectedPurchaser = _.find(t.usersSource, function(n) { return n.id === v.procurementPayOrder.purchaserId }), t.calcOrderPayAmount(), t.refreshTooltip(), v.procurementPayOrder.hasGroupSalesOrder || t.groupSalesEnabled && v.procurementPayOrder.status === y.ProcurementPayOrderStatus.PreCommit && v.procurementPayOrder.officeId !== l.officeId ? (t.isGroupSalesPayOrder = !0, n = _.pluck(t.procurementPayOrderProductItems, "productId"), it.getInventoryProductsCount({ productIds: n }).success(function(n) { n = n || {};
                _.each(t.procurementPayOrderProductItems, function(t) { t.inventoryCount = n[t.productId] || 0 }) })) : (t.editSupplier = _.find(t.dealersSource, function(n) { return n.name === v.procurementPayOrder.supplier }), t.skuAutoCompleteOptions.isLinkedCare = at(), t.lastSupplier = angular.copy(t.editSupplier), et().then(function(n) { var i = _.groupBy(n, "productId");
                _.each(t.procurementPayOrderProductItems, function(n) { n.dealers = i[n.productId] }) })), t.selectedOfficeIdsArray = [v.procurementPayOrder.officeId]) : t.groupSalesEnabled && t.source === y.ProcurementPayOrderSource.PurchaseApply ? (t.isGroupSalesPayOrder = !0, ot(), r = t.payOrderList[0], i = r.procurementOrders[0], _.each(t.procurementPayOrderProductItems, function(n) { i.procurementOrderItems.push(n) }), n = _.pluck(t.procurementPayOrderProductItems, "productId"), tt.getGroupSalesPrices(n).success(function(n) { n = n || {};
                _.each(t.procurementPayOrderProductItems, function(t) { t.price = (n[t.productId] || 0).toFixed(2);
                    t.amount = ((n[t.productId] || 0) * parseInt(t.number)).toFixed(2) });
                i.totalNum = i.procurementOrderItems.length;
                t.calcOrderPayAmount();
                t.refreshTooltip() }), it.getInventoryProductsCount({ productIds: n }).success(function(n) { n = n || {};
                _.each(t.procurementPayOrderProductItems, function(t) { t.inventoryCount = n[t.productId] || 0 }) })) : (et(!0).then(function(n) { st(n);
                ht() }), t.isShowOfficeSelector && (t.selectedOfficeIdsArray = ft.isGroupInventoryEnabled() ? [l.officeId] : []));
            vt() },
        vt = function() { t.showSyncDealer = !t.isGroupSalesPayOrder && t.canCreateSpu && t.canEditProcurementPrice && (!t.isEdit || t.isEdit && t.payOrderList[0].supplierType == 0) },
        yt = function(n, u) { var o, c, a, v, e, s, l, h; if (!n.isExist || n.dealers) { if (o = _.filter(t.procurementPayOrderProductItems, function(t) { return t.productId === n.productId }), o && o.length > 0 && !u && !n.dealers) { f.error("此物品已经在当前采购列表中！"); return } if (o && u) { _.each(t.payOrderList, function(t) { _.each(t.procurementOrders, function(t) { var i = _.find(t.procurementOrderItems, function(t) { return t.productId === n.productId });
                            i && i.number++ }) });
                    t.calcOrderPayAmount(); return } if (o && n.dealers && (c = _.find(n.dealers, function(n) { return n.isPreferred === !0 }), a = _.find(o, function(t) { return t.dealerId === c.dealerId && t.productId === n.productId }), a)) { v = _.find(t.payOrderList, function(n) { return n.supplierId === c.dealerId });
                    _.each(v.procurementOrders, function(t) { var i = _.find(t.procurementOrderItems, function(t) { return t.productId === n.productId });
                        i && (i.number = n.number) });
                    t.calcOrderPayAmount(); return } e = { productId: n.productId, barCode: n.barCode, name: n.name, price: n.price, number: n.number ? n.number : u ? 1 : 0, amount: u ? n.price : 0, producer: n.producer, specification: n.specification, unit: n.unit, isSynchronizeSupplier: !1, notes: "", dealers: n.dealers };
                n.isExist = !0;
                t.isGroupSalesPayOrder ? (t.procurementPayOrderProductItems.push(e), t.payOrderList.length === 0 && ot(), l = r.defer(), s = l.promise, h = [], h.push(it.getInventoryProductsCount({ productIds: [e.productId] }).then(function(n) { var t = n.data || {}; return e.inventoryCount = t[e.productId] || 0, !0 })), h.push(tt.getGroupSalesPrices([e.productId]).then(function(n) { var i = n.data || {}; return e.price = (i[e.productId] || 0).toFixed(2), e.amount = (parseFloat(e.price) * parseInt(e.number)).toFixed(2), t.payOrderList[0].procurementOrders[0].procurementOrderItems.unshift(e), !0 })), r.all(h).then(function() { l.resolve(e) })) : s = kt(e).then(function() { var i, n, u, o; return !t.canEditProcurementPrice && !t.isGroupSalesPayOrder && (_.isEmpty(e.dealers) || _.every(e.dealers, function(n) { return n.price == 0 })) ? (f.error("【" + e.name + "】没有设置供应商报价，不能添加到采购单明细"), r.reject(!1)) : (t.procurementPayOrderProductItems.push(e), t.isEdit ? (i = _.find(e.dealers, function(n) { return n.dealerName === t.editSupplier.name }), e.price = (i ? i.price : 0).toFixed(2), e.amount = (parseFloat(e.price) * parseInt(e.number)).toFixed(2), t.payOrderList[0].procurementOrders[0].procurementOrderItems.unshift(e)) : (n = _.find(e.dealers, function(n) { return n.isPreferred }), n ? (e.dealerId = n.dealerId, e.dealerName = n.dealerName, e.dealerType = n.dealerType, e.dealerCode = n.dealerCode, e.price = (n.price || 0).toFixed(2), e.amount = (parseFloat(e.price) * parseInt(e.number)).toFixed(2)) : (e.dealerId = 0, e.dealerName = "无供应商", e.dealerType = y.OrganizationType.NormalDealer, e.price = "0.00", e.amount = "0.00"), u = _.find(t.payOrderList, function(n) { return n.supplier === e.dealerName }), u ? u.procurementOrders[0].procurementOrderItems.unshift(e) : (o = { supplier: e.dealerName, supplierType: e.dealerType, supplierId: e.dealerId, supplierCode: e.dealerCode, procurementOrders: [{ totalNum: 0, totalAmount: 0, paymentAmount: 0, freight: 0, couponAmount: 0, procurementOrderItems: [e] }] }, n && (o.settlementMethod = n.settlementMethod), t.payOrderList.push(o), ct())), e) });
                s && s.then(function(n) { t.calcOrderPayAmount();
                    i.broadcast("SKU_SELECT_ADDED", { productId: n.productId });
                    u || d(function() { t.focusNextInput(null, n.productId) }, 0, !1);
                    t.refreshTooltip() }) } },
        pt = function() { _.each(t.procurementPayOrderProductItems, function(n) { var i = _.find(n.dealers, function(n) { return n.dealerName === t.editSupplier.name });
                i && (n.price = (i.price || 0).toFixed(2), n.amount = (parseFloat(n.price) * parseInt(n.number)).toFixed(2)) });
            t.calcOrderPayAmount() },
        ni = function() { if (t.editSupplier.type != y.OrganizationType.NormalDealer) pt();
            else { var n = [];
                _.each(t.procurementPayOrderProductItems, function(i) { var r = _.find(i.dealers, function(n) { return n.dealerName === t.editSupplier.name });
                    r && r.price > 0 && n.push(i) });
                n.length > 0 && s.confirm({ message: "检测到有" + n.length + "个物品在该供应商下有报价，需要更新这些物品的报价吗？" }).then(function() { pt() }) } },
        ti = function() { var i = t.selectedPurchaser,
                n = { orderDate: t.orderDate, createdOfficeId: t.createdOfficeId, isSyncToDealer: t.showSyncDealer ? t.isSyncToDealer.value : !1, purchaserId: null, purchaserName: null, isPushOrder: !1 }; return t.applyOrderParams ? _.extend(n, { officeId: t.applyOrderParams.officeId, source: y.ProcurementPayOrderSource.PurchaseApply }) : !t.payOrderList[0].hasGroupSalesOrder && t.isShowOfficeSelector && (n.officeId = t.selectedOfficeIdsArray[0]), i != null && i.id !== 0 && (n.purchaserId = i.id, n.purchaserName = i.name), n.orderDate = n.orderDate ? moment(n.orderDate).format("YYYY-MM-DD") : null, n },
        ii = function(n) { var i = ti();
            _.each(t.payOrderList, function(r) { if (_.extend(r, i), r.source = r.source || t.source, n ? (r.status = y.ProcurementPayOrderStatus.PreCommit, r.checkStatus = y.ProcurementPayOrderCheckStatus.PreSubmit, r.isPushOrder = !1) : (r.status = y.ProcurementPayOrderStatus.PreInStorage, r.checkStatus = y.ProcurementPayOrderCheckStatus.NoNeed, r.isPushOrder = r.supplierType != y.OrganizationType.NormalDealer), t.applyOrderParams) { var u = t.applyOrderParams.applyOrder,
                        f = [];
                    _.each(r.procurementOrders[0].procurementOrderItems, function(n) { var t = _.find(u.items, function(t) { return t.productId === n.productId });
                        t && f.push({ applyOrderId: u.id, applyOrderNo: u.orderNo, applyOrderItemId: t.id, productId: t.productId, count: n.number }) });
                    r.applyOrderItems = f } }) },
        ri = function() { i.on("SKU_SELECT_ADD", function(n) { if (n && n.data) { var i = n.data.sku;
                    i && (t.isEdit && t.editSupplier && t.editSupplier.type === y.OrganizationType.LinkedCare && !k.isLinkedCareProduct(i.barCode) ? f.error("当前供应商为领健，无法添加非领健物品") : yt(i)) } });
            i.on("TAB_SWITCHED", function() { var r = _.pluck(t.procurementPayOrderProductItems, "productId"),
                    n;
                i.broadcast("SKU_EXIST_LIST", { productIds: r });
                t.isEdit && !t.isGroupSalesPayOrder && (n = { isLinkedCare: t.editSupplier.type != y.OrganizationType.NormalDealer, dealerId: t.editSupplier.id }, i.broadcast("SUPPLIER_SELECTED", n)) }) },
        ui = function(n) { t.procurementPayOrderProductItems = n;
            et(!0).then(function(n) { st(n);
                ht() }) },
        fi = function() { wt().then(function() { bt().then(function() { gt();
                    ei() }) }) },
        ei = function() { return rt.getOfficeOption(rt.optionKeys.IsPurchaseProductImportEnabled).then(function(n) { t.isPurchaseProductImportEnabled = n }) };
    (function() { t.skuAutoCompleteOptions = { mode: "procurement", isLinkedCare: at(), isOnlyEnabled: !0 };
        t.createdOfficeId = l.officeId;
        t.saveProcurementOrder = dt;
        t.payOrderListSort = lt;
        t.isSyncToDealer = { value: !0 };
        t.usersSource = [];
        t.addSkuToList = yt;
        t.confirmUpdateProductPrices = ni;
        t.formatPayOrderList = ii;
        t.createGroupSalesPayOrder = ot;
        t.init = fi;
        t.checkShowSyncDealer = vt;
        t.addBatchProducts = ui;
        ri() })() }]);
supplychainModule.directive("procurementOrderGroupSupplierEditModalView", ["$timeout", "aresAccordionUtil", function(n, t) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-order-group-supplier-edit-modal/procurement-order-group-supplier-edit-modal-view.html", link: function(i, r) {
            function f() { n(function() { var n = { element: r, data: i.payOrders, secondDatakey: "procurementOrderItems", containerElement: ".table-main-content", tabElement: ".accordion-tab", rowHeight: 40, tabHeight: 24, scrollbarWidth: 10, parentTopOffset: 50 };
                    u = new t.AresAccordion(n);
                    u.init() }) }

            function e(n) { u.triggerTab(n) } var u;
            (function() { i.scrollAccordionTo = e;
                f() })() } } }]);
supplychainModule.controller("ProcurementOrderGroupSupplierEditModalCtrl", ["$scope", "dataDicSvc", "loginContext", "host", "enums", "officeOptionSvc", "aresNotification", "procurementSvc", "$modalInstance", "eventAggregator", "officeUtil", "permissionProvider", "inventoryUtil", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { "use strict";

    function y(n, t) { return t === void 0 && (t = 2), parseFloat(n.toFixed(t)) }

    function b() { n.payOrders = r.payOrders;
        n.supplier = r.supplier;
        n.isSyncToDealer = { value: !0, visible: !1 };
        p();
        t.currentOfficeWorkProviderDic.load().then(function(t) { t = _.filter(t, function(n) { return !n.isInactive && n.isShow !== !1 });
            t.unshift({ id: 0, name: "选择采购人" });
            n.usersSource = t; var r = i.providerId;
            n.selectedPurchaser = { id: r > 0 ? r : 0, name: i.userName } });
        a.checkCanEditProcurementPrice().then(function(t) { t ? c.isRootGroup().then(function(t) { n.isSyncToDealer.visible = t && l.isAllowed("product.productInfo") }) : n.isSyncToDealer.visible = !1 });
        f.getOfficeOption(f.optionKeys.IsNeedCheckAgreePrice).then(function(t) { n.isNeedCheckAgreePrice = t }) }

    function p() { n.totalAmount = n.payOrders.reduce(function(t, i) { var r = i.procurementOrders[0],
                f, e; return r.totalAmount = r.procurementOrderItems.reduce(function(n, t) { var i = y(t.price * t.number); return y(i + n) }, 0), f = typeof r.couponAmount == "string" ? parseFloat(r.couponAmount) : r.couponAmount, e = typeof r.freight == "string" ? parseFloat(r.freight) : r.freight, r.paymentAmount = y(r.totalAmount - f + e), i.paymentAmount = r.paymentAmount, i.actualAmount = n.supplier.settlementMethod === u.SettlementMethod.Instantly ? r.paymentAmount : 0, y(t + r.paymentAmount) }, 0) }

    function k() { v.confirm({ message: "暂存操作会将当前采购申请转成未确认的采购单，确定暂存吗？" }).then(function() { w(!0) }) }

    function w(t) { var i, r, h, f; if (!n.selectedPurchaser || !n.selectedPurchaser.id) return e.error("请选择采购人"); if (!n.payOrders[0].orderDate) return e.error("请填写采购日期"); if (i = _.find(n.payOrders, function(n) { return n.procurementOrders[0].paymentAmount < 0 }), i) return e.error("【" + i.officeName + "】的采购单折扣金额不能大于物品总额"); if (r = _.find(n.payOrders, function(n) { return n.actualAmount > n.procurementOrders[0].paymentAmount }), r) return e.error("【" + r.officeName + "】的采购单实付金额不能大于应付金额"); if (n.isNeedCheckAgreePrice && n.supplier.type !== u.OrganizationType.NormalDealer && (f = !1, angular.forEach(n.payOrders, function(n) { angular.forEach(n.procurementOrders[0].procurementOrderItems, function(n) { if (n.isNotAgreedProduct) { h = n.name;
                        f = !0; return } }) }), f)) return e.error("该物品【" + h + "】为非协议商品，无法去商城采购");
        n.payOrders.forEach(function(i) { i.isSyncToDealer = n.isSyncToDealer.value;
            i.purchaserId = n.selectedPurchaser.id;
            i.purchaserName = n.selectedPurchaser.name;
            t ? (i.status = u.ProcurementPayOrderStatus.PreCommit, i.checkStatus = u.ProcurementPayOrderCheckStatus.PreSubmit, i.isPushOrder = !1) : (i.status = u.ProcurementPayOrderStatus.PreInStorage, i.checkStatus = u.ProcurementPayOrderCheckStatus.NoNeed, i.isPushOrder = n.supplier.type !== u.OrganizationType.NormalDealer) });
        o.createPayOrderBatch(n.payOrders).success(function(n) { s.close(n);
            e.success("合并下单成功，请于采购订单页面查询") }).error(function(n) { var t;
            (n.name === "ArgumentException" || n.name === "InventoryOperationException") && (t = n.message);
            e.error(t || "操作失败") }) }

    function d(n, t) { t.stopPropagation();
        h.publish(h.events.ProductSelected, n.productId, t.delegateTarget) }(function() { b();
        n.calcTotalAmount = p;
        n.save = w;
        n.onSaveOnly = k;
        n.showProductPopup = d })() }]);
supplychainModule.directive("procurementOrderListView", ["$log", "$q", "$timeout", "appNav", "$modal", "aresSlidePanel", "$window", "aresNotification", "aresDialog", "enums", "eventAggregator", "dataDicSvc", "officeUtil", "loginContext", "procurementSvc", "aresModalShelf", "supplyChainPrintUtil", "procurementPayOrderUtil", "inventoryUtil", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d) { return { restrict: "E", templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-order-list-view/procurement-order-list-view.html", controller: "ProcurementOrderListCtrl", link: function(n, a) { var ft = function() { var i = t.defer(); return l.dealerDic.loadActive().then(function(t) { n.dealers = t;
                        n.dealers.splice(0, 0, { id: 0, name: "所属供应商" });
                        i.resolve(!0) }), i.promise },
                et = function(n) { var t = n.platformTradeNo || n.payOrderNo,
                        i = { action: h.ProcurementMallAction.Pay, tradeNo: t };
                    r.goToState("mallCenter", i) },
                ot = function() { g(); var n = angular.element(e);
                    a.find(".table-main").mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                    n.on("resize", function() { g() }) },
                g = function() { i(function() { var r = angular.element(e).height(),
                            i = r - 260 - (window.Ares3 ? 25 : 0),
                            t;
                        n.showAdvancedSearch && (i -= 64);
                        t = a.find(".table-main");
                        t.height(i);
                        t.mCustomScrollbar("update");
                        t.mCustomScrollbar("scrollTo", "top") }) },
                st = function(n) { n.isShowTips = !n.isShowTips },
                ht = function(n, t) { t.stopPropagation();
                    n.isShowTips = !n.isShowTips },
                ct = function(n, t) { var i = n.productId || item.id;
                    c.publish(c.events.ProductSelected, i, t.delegateTarget) },
                lt = function(n) { var t = window.event ? n.keyCode : n.which;
                    t == 13 && nt() },
                nt = function() { var r = t.defer(); return n.searchProcurementOrder().then(function() { i(function() { g();
                            r.resolve() }) }), r.promise },
                at = function(n) { var t = u.open({ animation: !0, backdrop: "static", template: "<procurement-way-bill-order-view><\/procurement-way-bill-order-view>", controller: "ProcurementWayBillOrderCtrl", windowClass: "modal-1000w-dialog", resolve: { host: function() { return { waybills: n.waybills, payOrderType: n.type } } } });
                    t.result.then(function() {}) },
                it = function() { var t = p.open({ title: "新增采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-edit-modal-view><\/procurement-order-edit-modal-view>", controller: "ProcurementOrderEditModalCtrl", resolve: { dataHost: function() { return { source: h.ProcurementPayOrderSource.Manual, isNewAdd: !0 } } }, confirmClose: !0 });
                    t.result.then(function(t) { n.initPayOrderStatusSummaryHints();
                        n.searchProcurementOrder();
                        t && tt(t) }) },
                rt = function(t) { n.pushPltOrder(t.id).then(function() { tt(t.payOrderNo + ":" + t.officeId) }, function(n) { n && n.name === "InventoryOperationException" ? o.error(n.message) : o.error("推送订单信息至交易平台出错！") }) },
                ut = function(t) { t.isLinkedCare ? rt(t) : d.warn({ message: "确认下单后，会下推待入库单让库管准备收货入库，确定下单吗？", onConfirm: function() { t.status = h.ProcurementPayOrderStatus.PreInStorage;
                            t.checkStatus = h.ProcurementPayOrderCheckStatus.Pending;
                            n.commitProcurementOrder(t).then(function() { n.searchProcurementOrder() }) }, onCancel: function() {} }) },
                tt = function(t) { var i = f.open("<procurement-order-mall-cart-view><\/procurement-order-mall-cart-view>", "ProcurementOrderMallCartCtrl", { dataHost: function() { return { payOrderNo: t.split(":")[0], ownerOfficeId: t.split(":")[1] } } }, n);
                    i.result.then(function(n) { if (n && n.isOrderDone) { if (!t) return; var i = t.split(":")[0]; if (!i) return;
                            y.updatePayOrderStatusByPayOrderNo(i, h.ProcurementPayOrderStatus.Committing).then(function() { nt() }) } }) },
                vt = function() { n.isGroup = v.isGroup },
                yt = function() { r.goToState("supplychain.procurement.groupOrder") },
                pt = function() { n.searchCriteria.orderDate_SearchBegin = n.searchTimeRange.startDate;
                    n.searchCriteria.orderDate_SearchEnd = n.searchTimeRange.endDate;
                    nt() },
                wt = function(t) { w.printProcurementOrder(t, n) },
                bt = function(t) { n.selectedOfficeIdsArray = _.pluck(t, "officeId");
                    n.searchProcurementOrder() },
                kt = function() { n.searchProcurementOrder() },
                dt = function(n) { b.goToInOrder(n) },
                gt = function(t) { var r = p.open({ title: "采购单详情", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-detail-view><\/procurement-order-detail-view>", controller: "ProcurementOrderDetailCtrl", resolve: { host: function() { return { payOrderId: t.id, groupSalesEnabled: n.groupSalesEnabled } } } });
                    r.result.then(function(t) { n.initPayOrderStatusSummaryHints();
                        n.searchProcurementOrder();
                        t && t.furtherAction === "edit" && t.payOrderId ? ni(t.payOrderId) : t && t.furtherAction === "copy" && t.newPayOrder ? ti(t.newPayOrder) : t && t.furtherAction === "commit" && t.payOrder && i(function() { ut(t.payOrder) }, 600, !1) }) },
                ni = function(t) { n.getPayOrderDetail(t).then(function(t) { var r = t.procurementOrders[0].procurementOrderItems,
                            i;
                        r.forEach(function(n) { n.producer = n.producter });
                        i = p.open({ title: "编辑采购单", titleIconClass: "iconfont icon-bianji", template: "<procurement-order-edit-modal-view><\/procurement-order-edit-modal-view>", controller: "ProcurementOrderEditModalCtrl", resolve: { dataHost: function() { return { procurementPayOrder: t } } }, confirmClose: !0 });
                        i.result.then(function(t) { n.initPayOrderStatusSummaryHints();
                            n.searchProcurementOrder();
                            t && angular.isObject(t) && t.isPushOrder && t.payOrderNo && tt(t.payOrderNo + ":" + t.officeId) }) }) },
                ti = function(t) { var i = p.open({ title: "新增采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-edit-modal-view><\/procurement-order-edit-modal-view>", controller: "ProcurementOrderEditModalCtrl", resolve: { dataHost: function() { return { procurementPayOrder: t } } }, confirmClose: !0 });
                    i.result.then(function(t) { n.initPayOrderStatusSummaryHints();
                        n.searchProcurementOrder();
                        t && angular.isString(t) && tt(t) }) },
                ii = function() { var n = p.open({ title: "新增对账单", titleIconClass: "iconfont icon-xiaofei", template: "<procurement-settlement-order-edit-view><\/procurement-settlement-order-edit-view>", controller: "ProcurementSettlementOrderEditCtrl", resolve: { host: function() { return {} } }, confirmClose: !0 });
                    n.result.then(function() {}) },
                ri = function(n) { var t = { action: h.ProcurementMallAction.OrderDetail, orderSn: n };
                    r.goToState("mallCenter", t) },
                ui = function() { n.procuementOrderTotalCount <= 0 || n.invokePayOrderListToZip().then(function(n) { s.info("信息", n) }, function() { o.error("列表导出失败，请重试！") }) };
            (function() { n.isHideAddOrderBtn = v.isGroup && !v.isRootGroup && v.officeType == 1;
                n.onEnter = lt;
                n.initTableView = g;
                n.onSelectProduct = ct;
                n.onSearchProcuementOrder = nt;
                n.goToPay = et;
                n.showWayBillOrderDialog = at;
                n.createProcurementOrder = it;
                n.goToLCCart = rt;
                n.onGroupTabsSwitchClick = yt;
                n.currentOfficeId = v.officeId;
                n.commitPayOrder = ut;
                n.onSearchTimeRangeChanged = pt;
                n.onSearchStatusChange = kt;
                n.goToInOrder = dt;
                n.printPayOrder = wt;
                n.onOfficeSelected = bt;
                n.viewPayOrderDetail = gt;
                n.moveToTips = st;
                n.leaveToTips = ht;
                n.createSettlementOrder = ii;
                n.goToMallOrderDetail = ri;
                n.showAdvancedSearch = !1;
                n.triggerPayOrderListToZip = ui;
                ot();
                vt();
                n.loadOffices().then(function() { k.getGroupProcurementConfigs().then(function(t) { n.groupSalesEnabled = t.groupSalesEnabled });
                    ft().then(function() { n.selDealer = 0;
                        n.initDefaultData();
                        n.openEditModalDirectly && it() }) }) })() } } }]);
supplychainModule.controller("ProcurementOrderListCtrl", ["$log", "$scope", "$filter", "$timeout", "$stateParams", "aresConfirmDialog", "loginContext", "permissionProvider", "procurementSvc", "workflowSvc", "aresNotification", "$q", "appNav", "dataDicSvc", "enums", "reportUtil", "inventoryUtil", "officeUtil", "$sce", "officeSvc", "officeSelectorUtil", "procurementPayOrderUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt) { "use strict";

    function tt() { var n = angular.copy(t.searchCriteria); return n.orderDate_SearchBegin = moment(n.orderDate_SearchBegin).format("YYYY-MM-DD"), n.orderDate_SearchEnd = moment(n.orderDate_SearchEnd).add(1, "days").format("YYYY-MM-DD"), n.payOrderNo = t.searchCriteria.payOrderNo, n.searchText = t.searchCriteria.searchText, n.officeIds = t.isGroup ? t.selectedOfficeIdsArray : [e.officeId], t.selDealer != "0" ? n.supplierId = t.selDealer : n.supplier = "", t.searchStatus && (t.searchStatus == 0 ? n.status = -100 : t.searchStatus == 1 ? n.isOnlyPreInStorage = !0 : t.searchStatus == 5 ? n.isOnlyPreCommit = !0 : n.status = t.searchStatus), n } var ut = function() { ft();
            v.workflowDefinitionDic.load().then(function(n) { return t.procurementPayWorkflow = _.find(n, function(n) { return n.workflowType == y.WorkflowType.ProcurementPay && !n.isDisabled == !0 }), it() }).then(function() { r(function() { t.initTableView() }) }) },
        ft = function() { var n = p.getDefaultTimeSpan();
            t.searchTimeRange = { startDate: n.startTime, endDate: n.endTime };
            t.searchCriteria = { orderDate_SearchBegin: t.searchTimeRange.startDate, orderDate_SearchEnd: t.searchTimeRange.endDate, status: -100, orderNumber: "", pageIndex: 0, pageSize: 10 } },
        it = function() { var i = tt(),
                n = l.defer(); return s.searchProcurementOrder(i).then(function(i) { t.procuementOrderList = et(i.data.page.items);
                t.procuementOrderTotalCount = i.data.page.totalCount;
                t.totalResult = i.data.totalResult;
                r(function() { t.initTableView() });
                n.resolve(!0) }), n.promise },
        et = function(n) { return angular.forEach(n, function(n) { var i = _.find(t.offices, function(t) { return t.id == n.officeId });
                n.officeName = i.abbreviation;
                n.orderDateStr = moment(n.orderDate).format("YYYY-MM-DD");
                n.isLinkedCare = n.type == y.ProcurementOrderType.LinkedCare;
                angular.isString(n.platformOrderNos) && (n.platformOrderNoArray = n.platformOrderNos.split(","));
                n.showSettlementInfo = n.status === y.ProcurementPayOrderStatus.Pending || n.status === y.ProcurementPayOrderStatus.PreCommit || n.status === y.ProcurementPayOrderStatus.Committing || n.checkStatus === y.ProcurementPayOrderCheckStatus.Pending || n.checkStatus === y.ProcurementPayOrderCheckStatus.PreSubmit || n.checkStatus === y.ProcurementPayOrderCheckStatus.Rejected ? !1 : !0;
                n.showPlatformOrder = n.isLinkedCare && n.platformOrderNos }), ni(n), n },
        ot = function() { var n = l.defer(); return v.userNameDic.load().then(function(i) { t.users = i;
                n.resolve(!0) }), n.promise },
        st = function() { var n = l.defer(),
                i = [v.officeDic.load().then(function(n) { t.offices = n })]; return t.isGroup && i.push(d.getSelfAndChildOfficesByGroupId(e.officeId, !0).success(function(n) { t.officeTreeData = g.setId(n); var i = _.values(g.flattenToMap(n));
                t.selectedOfficeIdsArray = _.pluck(i, "officeId") })), l.all(i).then(function() { n.resolve(!0) }), n.promise },
        ht = function(n) { var t = { action: y.ProcurementMallAction.Pay, tradeNo: n.payOrderNo };
            a.goToState("mallCenter", t) },
        ct = function(n) { a.goToInTradeOrder(n) },
        lt = function(n) { var i = l.defer(); return s.cancelPayOrder(n.id).success(function(n) { n ? (t.searchProcurementOrder(), c.success("操作成功")) : c.error("操作失败");
                i.resolve(!0) }).error(function(n) { n && (n.name == "InventoryOperationException" || n.name == "AresBusinessException") ? c.error(n.message) : c.error("操作失败!") }), i.promise },
        at = function(n) { f.confirm({ message: "确定作废当前采购订单？" }).then(function() { lt(n) }) },
        vt = function(n) { f.confirm({ message: "确定提交审批此采购单" }).then(function() { return wt(n) }).then(function() { t.onSearchProcuementOrder() }) },
        yt = function(n) { return n.createdOfficeId === t.currentOfficeId && n.status !== y.ProcurementPayOrderStatus.PreCommit && n.status !== y.ProcurementPayOrderStatus.Committing && n.checkStatus === y.ProcurementPayOrderCheckStatus.PreSubmit },
        pt = function(n) { return o.isAllowed("inventoryOperation.stockInBrowser") && n.officeId === t.currentOfficeId && (n.status === 1 || n.status === 2) && (n.checkStatus == y.ProcurementPayOrderCheckStatus.NoNeed || n.checkStatus == y.ProcurementPayOrderCheckStatus.Checked) },
        wt = function(n) { var t = l.defer(); return h.startProcurementPayOrderWorkflow(n.id).then(function() { c.success("审批提交成功");
                t.resolve() }).catch(function(n) { var t = n.data;
                c.error("审批提交失败") }), t.promise },
        bt = function(n) { var t = !1; return (n.checkStatus == y.ProcurementPayOrderCheckStatus.NoNeed || n.checkStatus == y.ProcurementPayOrderCheckStatus.Checked) && (n.status == y.ProcurementPayOrderStatus.PreInStorage || n.status == y.ProcurementPayOrderStatus.PartInStorage) && (t = n.isLinkedCare && !n.hasWayBill ? !1 : !0), t },
        kt = function(n) { var t = l.defer(); return s.pushPltOrder(n).success(function() { t.resolve(!0) }).error(function(n) { t.reject(n) }), t.promise },
        dt = function() { w.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        gt = function(n) { var t = l.defer(),
                i = s.updateProcurementPayOrder; return i(n).then(function(n) { n.checkStatus === y.ProcurementPayOrderCheckStatus.PreSubmit ? f.confirmAction({ message: "该订单需要审批，是否提交审批？您也可以暂时保存该订单，稍后再提交。", confirmText: "提交审批", cancelText: "保存" }).then(function() { h.startProcurementPayOrderWorkflow(n.id).success(function() { c.success("已成功提交审批");
                        deferred.resolve(!0) }) }, function() { c.success("保存成功");
                    deferred.resolve(!0) }) : (c.success("保存成功"), t.resolve(n)) }, function(n) { var i = n.data;
                i.name == "ArgumentException" ? c.error(i.message) : i.name == "InventoryOperationException" ? c.error(i.message) : t.reject(i) }), t.promise },
        ni = function(n) { _.each(n, function(n) { n.statusLabel = nt.getStatusLabelHtml(n) }) },
        rt = function() { var n = { payOrderStatus: [1, 5] };
            n.officeIds = t.isGroup ? t.selectedOfficeIdsArray : [e.officeId];
            s.getProcurementPayorderStatusSummary(n).success(function(n) { t.payorderStatusSummaryHits = { preCommit: n.preCommit, preInStorage: n.preInStorage } }) },
        ti = function() { b.getGroupProcurementMethod().then(function(n) { t.selfProcurementEnabled = n !== "group" || e.isRootGroup }) },
        ii = function() { b.checkSelfSettlementEnabled().then(function(n) { t.selfSettlementEnabled = n }) },
        ri = function(n) { var t = l.defer(); return s.getPayOrderFullById(n).success(function(n) { t.resolve(n) }), t.promise },
        ui = function(n, t) { nt.exportExcel(n, t) },
        fi = function() { var i = tt(),
                n; return i.totalItemCount = t.procuementOrderTotalCount, n = l.defer(), s.invokePayOrderListToZip(i).success(function(t) { var i = t.isSucceed ? t.hasTaskCancelled ? "后台报表'" + t.newTask.reportName + "'已创建！（已取消10分钟内同类报表）" : "后台报表'" + t.newTask.reportName + "'已创建！" : "已存在处理的同类型的报表（10分钟内只能创建一个同类型报表）！";
                n.resolve(i) }).error(function(t) { n.reject(t) }), n.promise };
    (function() { t.inOrder = ct;
        t.commitProcurementOrder = gt;
        t.searchProcurementOrder = it;
        t.goToPay = ht;
        t.loadOffices = st;
        t.loadUsers = ot;
        t.initDefaultData = ut;
        t.onCancelProcuementOrder = at;
        t.canSubmit = yt;
        t.canInOrder = pt;
        t.onSubmitProcurementOrder = vt;
        t.checkCanInInventory = bt;
        t.pushPltOrder = kt;
        t.openEditModalDirectly = u.openEditModalDirectly;
        t.searchStatus = 0;
        t.initPayOrderStatusSummaryHints = rt;
        t.getPayOrderDetail = ri;
        t.exportExcel = ui;
        t.invokePayOrderListToZip = fi;
        ti();
        ii();
        dt();
        rt() })() }]);
supplychainModule.directive("procurementReturnOrderOtherLcDialogView", ["$log", "$modal", "$timeout", "loginContext", "aresNotification", function(n, t, i, r, u) { "use strict"; return { restrict: "E", replace: !1, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-return-order/procurement-return-order-other-lc-dialog-view.html", link: function(n, t) { var h = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 100) },
                c = function() { var t, i, r; if (Ares.ensureNotDuplicated("ProcurementReturnOrderOtherSaveCheck")) { if (t = n.payOrderItem, !_.isBoolean(n.isInStorage)) { u.error("请选择退货类型"); return } if (!n.notes) { u.error("请注明退货原因"); return } if (n.returnCount === 0) { u.error("请填写退货数量"); return } if (n.actualAmount != "" && parseFloat(n.actualAmount) > parseFloat(n.returnAmount)) { u.error("实收总额不能大于退货总额"); return } if (n.isInStorage) { if (n.returnCount > t.inStorageNum - t.returnCountInstorage) { u.error("已入库数量不能大于库存数量"); return } } else if (n.returnCount > t.unInStorageNum) { u.error("未入库数量不能大于库存数量"); return } i = parseFloat(n.returnAmount);
                        r = [{ procurementOrderId: t.orderId, procurementPayOrderId: t.payOrderId, procurementPayOrderNo: t.payOrderNo, type: n.isInStorage ? 2 : 1, notes: n.notes, officeId: t.officeId, actualAmount: parseFloat(n.actualAmount), amount: i, items: [{ procurementOrderItemId: t.id, productId: t.productId, count: n.returnCount, amount: i, purchaseAmount: t.avgCostPrice * n.returnCount }] }];
                        n.saveReturnOrderForm(r) } },
                l = function() { var t = n.returnCount,
                        i = n.payOrderItem.unInStorageNum;
                    n.returnCount = t >= 0 && t <= i ? t : 0;
                    e() },
                a = function() { var t = n.returnCount,
                        i = parseInt(n.payOrderItem.inStorageNum) - parseInt(n.payOrderItem.returnCountInstorage);
                    n.returnCount = t >= 0 && t <= i ? t : 0;
                    e() },
                o = function() { n.isInStorage ? a() : l() },
                r = function(n) { return /^[0-9]+([.]{1}[0-9]{1,2})?$/.test(n) ? parseFloat(n) : 0 },
                s = function() { parseFloat(n.returnPrice) > parseFloat(n.payOrderItem.avgCostPrice) && (u.error("退货单价不能大于平均单价"), n.returnPrice = 0) },
                e = function() { var t = r(n.returnPrice);
                    t !== 0 && (s(), n.returnAmount = Number(n.returnPrice * n.returnCount).toFixed(2), f()) },
                v = function() { var t = r(n.returnAmount);
                    t !== 0 && (f(), n.returnCount > 0 && (n.returnPrice = Number(n.returnAmount / n.returnCount).toFixed(2), s())) },
                y = function(t) { n.isInStorage != t && (n.isInStorage = t, n.returnCount = 0, n.returnAmount = 0, f(), o()) },
                p = function(t) { var i, u, e; if (t) { i = r(n.actualAmount);
                        i == 0 && (n.actualAmount = 0); return } u = r(n.returnPrice);
                    e = r(n.returnAmount);
                    (u === 0 || e === 0) && (n.returnPrice = 0, n.returnAmount = 0, f()) },
                f = function() { n.settlementMethod === 0 && (n.actualAmount = n.returnAmount) },
                w = function() { n.payOrderItem.unInStorageNum = n.payOrderItem.number - n.payOrderItem.inStorageNum - n.payOrderItem.returnCountPreInstorage - n.payOrderItem.returnCountPreDeliver };
            (function() { n.save = c;
                n.isInStorage = undefined;
                n.changeType = y;
                n.checkNumber = p;
                n.calculReturnCount = o;
                n.calculAmount = e;
                n.calculPrice = v;
                n.setActualAmount = f;
                n.returnCount = 0;
                n.returnPrice = n.payOrderItem.avgCostPrice ? n.payOrderItem.avgCostPrice : "";
                n.settlementMethod = n.payOrderItem.settlementMethod;
                n.returnAmount = 0;
                n.actualAmount = 0;
                n.notes = "";
                h();
                w() })() } } }]);
supplychainModule.controller("ProcurementReturnOrderOtherLcDialogCtrl", ["$q", "$log", "$scope", "$modalInstance", "host", "loginContext", "aresNotification", "procurementSvc", "aresDialog", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function() { r.dismiss() },
        h = function(n) { o.saveProcurementReturnOrders(n).then(function(n) { r.close(n);
                e.success("保存成功") }) };
    (function() { i.payOrderItem = angular.copy(u.payOrderItem);
        i.isGroupSalesOrder = u.isGroupSalesOrder;
        i.closeModal = s;
        i.saveReturnOrderForm = h })() }]);
supplychainModule.directive("procurementReturnOrderEditDialogView", ["$log", "$modal", "$timeout", "loginContext", "aresNotification", function(n, t, i, r, u) { "use strict"; return { restrict: "E", replace: !1, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-return-order-edit-dialog/procurement-return-order-edit-dialog-view.html", link: function(n, t) { var f = function() { i(function() { Ares.centerModal(t.closest(".modal-dialog")) }, 100) },
                r = function(n) { return /^[0-9]+([.]{1}[0-9]{1,2})?$/.test(n) ? parseFloat(n) : 0 },
                e = function() { var t, o, s, e, h, i, f; if (Ares.ensureNotDuplicated("ProcurementReturnOrderSaveCheck")) { if (t = n.payOrderItem, !n.notes) { u.error("请注明退货原因"); return } if (o = r(n.storageNum.preInstorage), s = r(n.storageNum.instorage), o === 0 && s === 0) { u.error("请填写退货数量"); return } if (o + s != n.returnCount) { u.error("未入库加已入库总数量必须等于退货数量"); return } if (e = [], h = { procurementOrderId: t.orderId, procurementPayOrderId: t.payOrderId, procurementPayOrderNo: t.payOrderNo, procurementReturnApplyOrderId: t.returnApplyOrder.id, officeId: t.officeId, notes: n.notes, items: [{ procurementOrderItemId: t.id, productId: t.productId }] }, n.storageNum.preInstorage > 0) { if (n.storageNum.preInstorage > t.unInStorageNum) { u.error("未入库数量不能大于库存数量"); return } i = angular.copy(h);
                            i.type = 1;
                            i.items[0].count = n.storageNum.preInstorage;
                            i.items[0].amount = n.storageNum.instorage > 0 ? n.returnPrice * n.storageNum.preInstorage : n.returnAmount;
                            i.items[0].purchaseAmount = t.avgCostPrice * n.storageNum.preInstorage;
                            n.isLinkedCare && (i.items[0].amount = 0);
                            e.push(i) } if (n.storageNum.instorage > 0) { if (n.storageNum.instorage > t.inStorageNum - t.returnCountInstorage) { u.error("已入库数量不能大于库存数量"); return } f = angular.copy(h);
                            f.type = 2;
                            f.items[0].count = n.storageNum.instorage;
                            f.items[0].amount = n.returnAmount - n.returnPrice * n.storageNum.preInstorage;
                            f.items[0].purchaseAmount = t.avgCostPrice * n.storageNum.instorage;
                            n.isLinkedCare && (f.items[0].amount = 0);
                            e.push(f) } n.saveReturnOrderForm(e) } },
                o = function() { var t = n.storageNum.preInstorage,
                        i = n.payOrderItem.unInStorageNum;
                    n.storageNum.preInstorage = t >= 0 && t <= i ? isNaN(parseInt(t)) ? 0 : parseInt(t) : 0 },
                s = function() { var t = n.storageNum.instorage,
                        i = parseInt(n.payOrderItem.inStorageNum) - parseInt(n.payOrderItem.returnCountInstorage);
                    n.storageNum.instorage = t >= 0 && t <= i ? isNaN(parseInt(t)) ? 0 : parseInt(t) : 0 },
                h = function() { n.payOrderItem.unInStorageNum = n.payOrderItem.number - n.payOrderItem.inStorageNum - n.payOrderItem.returnCountPreInstorage - n.payOrderItem.returnCountPreDeliver };
            (function() { n.save = e;
                n.countPreInstorage = o;
                n.countInstorage = s;
                n.storageNum = { preInstorage: "", instorage: "" };
                n.returnCount = n.payOrderItem.returnApplyOrder ? n.payOrderItem.returnApplyOrder.count : 0;
                n.returnPrice = n.payOrderItem.avgCostPrice ? n.payOrderItem.avgCostPrice : "";
                n.returnAmount = "";
                n.notes = n.payOrderItem.returnApplyOrder ? n.payOrderItem.returnApplyOrder.notes : "";
                f();
                h() })() } } }]);
supplychainModule.controller("ProcurementReturnOrderEditDialogCtrl", ["$q", "$log", "$scope", "$modalInstance", "host", "loginContext", "aresNotification", "procurementSvc", "aresDialog", function(n, t, i, r, u, f, e, o) { "use strict";
    i.payOrderItem = angular.copy(u.payOrderItem);
    i.isLinkedCare = u.isLinkedCare; var s = function() { r.dismiss() },
        h = function(n) { o.saveProcurementReturnOrders(n).then(function(n) { r.close(n);
                e.success("保存成功") }) };
    (function() { i.payOrderItem.returnApplyOrder || angular.forEach(i.payOrderItem.returnOrderItems, function(n) { n.isAlreadyHandler || (i.payOrderItem.returnApplyOrder = n, i.payOrderItem.returnApplyOrder.id = n.returnApplyOrderId) });
        i.closeModal = s;
        i.saveReturnOrderForm = h })() }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n() { this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/procurement/dialogs/procurement-settlement-invoice-list-view/procurement-settlement-invoice-list-view.html";
            this.link = function() {
                (function() {})() } } return n.$inject = [], n }();
    supplychainModule.directive("procurementSettlementInvoiceListView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f) { var e = this;
            this.$scope = n;
            this.host = t;
            this.enums = i;
            this.aresNotification = r;
            this.procurementSvc = u;
            this.$modalInstance = f;
            n.pictureUploadCallbacks = [];
            this._settlementOrder = t.settlementOrder;
            _.each(this._settlementOrder.invoices, function(n) { n.invoiceDate = moment(n.invoiceDate).format("YYYY-MM-DD");
                n.pictureUrl && e._settlementOrder.supplierType === 0 && (n.pictureUrl = encodeURIComponent(n.pictureUrl)) });
            n.canEdit = this._settlementOrder.supplierType === 0 && this._settlementOrder.status !== this.enums.ProcurementSettleStatus.Settled;
            n.invoices = this._settlementOrder.invoices || [];
            this._updateUploadCallbacks() } return n.prototype.addInvoice = function() { this.$scope.invoices.push({ hostType: this.enums.InvoiceHostType.ProcurementSettlementOrder, hostId: this._settlementOrder.id, hostNo: this._settlementOrder.orderNo, invoiceType: this.enums.InvoiceType.Common, amount: 0, invoiceNo: "", invoiceDate: "", isEdit: !0 }); var n = this.$scope.invoices.length - 1;
            this._updateUploadCallbacks() }, n.prototype.save = function() { var t = this,
                n, i = _.find(this.$scope.invoices, function(t) { return t.invoiceNo ? t.invoiceDate ? t.invoiceDate.match(/^\d{4}-\d{2}-\d{2}$/) ? !t.amount || parseFloat(String(t.amount)) === 0 ? (n = "请填写发票金额", !0) : !!n : (n = "开票时间格式不正确", !0) : (n = "请填写开票时间", !0) : (n = "请填写发票编号", !0) }); if (n) { this.aresNotification.error(n); return } _.each(this.$scope.invoices, function(n) { n.hostType = t.enums.InvoiceHostType.ProcurementSettlementOrder;
                n.hostId = t._settlementOrder.id;
                n.hostNo = t._settlementOrder.orderNo });
            this.procurementSvc.saveSettlementInvoices({ settlementOrderNo: this._settlementOrder.orderNo, invoices: this.$scope.invoices }).success(function() { t.aresNotification.success("保存成功");
                t.$modalInstance.close(!0) }).error(function() { t.aresNotification.error("保存失败") }) }, n.prototype.delete = function(n) { this.$scope.invoices.splice(n, 1);
            this._updateUploadCallbacks() }, n.prototype.deletePicture = function(n) { n.pictureId = null }, n.prototype._updateUploadCallbacks = function() { var n = this;
            _.each(this.$scope.invoices, function(t, i) { n.$scope.pictureUploadCallbacks[i] = function(n) { t.pictureId = n.id;
                    t.pictureUrl = encodeURIComponent(n.filePath);
                    console.log(n, i) } }) }, n.$inject = ["$scope", "host", "enums", "aresNotification", "procurementSvc", "$modalInstance"], n }();
    supplychainModule.controller("ProcurementSettlementInvoiceListCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n) { this.$timeout = n;
            this.replace = !0;
            this.restrict = "E";
            this.templateUrl = "/app/supplychain/views/procurement/dialogs/procurement-settlement-order-detail-view/procurement-settlement-order-detail-view.html";
            this.scope = !0;
            this.controller = "@";
            this.name = "controllerName";
            this.link = function(n, t, i) { var r = t.find(".table-container"),
                    u = function() { r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } }) };
                (function() { n.updateScrollbar = u;
                    n.$watch(function() { return i.orderNo }, function() { i.orderNo && (n._orderNo = i.orderNo) }) })() } } return n.$inject = ["$timeout"], n }();
    supplychainModule.directive("procurementSettlementOrderDetailView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s) { var h = this;
            this.$scope = n;
            this.procurementSvc = t;
            this.enums = i;
            this.$sce = r;
            this.inventoryUtil = u;
            this.loginContext = f;
            this.$timeout = e;
            this.aresModalShelf = o;
            this.appNav = s;
            n.isRootGroup = f.isGroup && f.isRootGroup;
            this.initProductCodeOptions();
            n.$watch("_orderNo", function(n) { n && h.getOrderDetail() }) } return n.prototype.getOrderDetail = function() { var n = this;
            this.procurementSvc.getSettlementOrderDetail(this.$scope._orderNo).success(function(t) { var i = t[0],
                    u = _.groupBy(i.items, "referenceOrderOfficeId"),
                    r = [];
                _.each(u, function(t, u) { t = _.sortBy(t, "referenceOrderDate"); var f = 0,
                        e = 0;
                    _.each(t, function(t) {
                        (i.supplierType === n.enums.OrganizationType.LinkedCare || i.supplierType === n.enums.OrganizationType.MallDealer) && (t.platformTradeNoArray = t.platformTradeNo.split(",")); var r = 0;
                        _.each(t.details, function(n) { f += n.count;
                            r += n.amount - n.orderCouponShare });
                        t.lcTotalAmount = r;
                        e += t.totalAmount;
                        t.expanded = !1 });
                    r.push({ items: t, expanded: !0, totalCount: f, totalAmount: e, officeId: u, canPay: moment(i.orderDate).isAfter(moment("2019-03-01")) && t[0].status != 2 && t[0].platformSettlementOrderNo }) });
                i.officeGroups = r;
                n.$scope.order = i;
                n.setSubTableColSpan();
                n.$timeout(function() { n.$scope.updateScrollbar() }) }) }, n.prototype.setSubTableColSpan = function() { var n = this.$scope.order;
            this.$scope.subTableColSpan = n.status === this.enums.ProcurementSettleStatus.Settled ? n.supplierType === this.enums.OrganizationType.NormalDealer ? n.settlementMode === this.enums.ProcurementSettlementMode.ByOrder ? 6 : 7 : n.settlementMode === this.enums.ProcurementSettlementMode.ByOrder ? 7 : 8 : n.supplierType === this.enums.OrganizationType.NormalDealer ? n.settlementMode === this.enums.ProcurementSettlementMode.ByOrder ? 8 : 9 : n.settlementMode === this.enums.ProcurementSettlementMode.ByOrder ? 9 : 10 }, n.prototype.initProductCodeOptions = function() { var n = this;
            this.inventoryUtil.getProductCodeOptions().then(function(t) { n.$scope.allowInsideCode = t.allowInsideCode }) }, n.prototype.onToggleOfficeExpand = function(n) { var t = this;
            n.expanded = !n.expanded;
            _.each(n.items, function(t) { t.hidden = !n.expanded });
            this.$timeout(function() { t.$scope.updateScrollbar() }) }, n.prototype.onSubTableExpand = function(n) { var t = this;
            n.expanded = !n.expanded;
            this.$timeout(function() { t.$scope.updateScrollbar() }) }, n.prototype.showProcurementOrderDetail = function(n) { this.aresModalShelf.open({ title: "采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-detail-view><\/procurement-order-detail-view>", controller: "ProcurementOrderDetailCtrl", resolve: { host: function() { return { payOrderId: n } } }, needActive: !0 }) }, n.prototype.goToPay = function(n) { var t = { action: this.enums.ProcurementMallAction.Pay, settlementOrderNo: n };
            this.appNav.goToState("mallCenter", t) }, n.prototype.goToMallOrderDetail = function(n) { var t = { action: this.enums.ProcurementMallAction.OrderDetail, orderSn: n };
            this.appNav.goToState("mallCenter", t) }, n.prototype.goToMallServiceDetail = function(n) { var t = { action: this.enums.ProcurementMallAction.ServiceOrder, serviceSn: n };
            this.appNav.goToState("mallCenter", t) }, n.$inject = ["$scope", "procurementSvc", "enums", "$sce", "inventoryUtil", "loginContext", "$timeout", "aresModalShelf", "appNav"], n }();
    supplychainModule.controller("ProcurementSettlementOrderDetailCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n() { this.replace = !0;
            this.restrict = "E";
            this.templateUrl = "/app/supplychain/views/procurement/dialogs/procurement-settlement-order-edit-detail-view/procurement-settlement-order-edit-detail-view.html";
            this.link = function(n, t) { var i = t.find(".table-container"),
                    r = function() { i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) };
                (function() { n.updateScrollbar = r })() } } return n.$inject = [], n }();
    supplychainModule.directive("procurementSettlementOrderEditDetailView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c) { this.$scope = n;
            this.host = t;
            this.procurementSvc = i;
            this.procurementPayOrderUtil = r;
            this.inventoryUtil = u;
            this.eventAggregator = f;
            this.$timeout = e;
            this.loginContext = o;
            this.aresNotification = s;
            this.$modalInstance = h;
            this.enums = c;
            this.round = function(n) { var t = typeof n == "string" ? parseFloat(n) : n; return Math.round((t + 1e-10) * 100) / 100 };
            n.isGroup = o.isGroup;
            n.inStorageProductOnly = !1;
            this.getProcurementOrderDetail();
            this.initProductCodeOptions() } return n.prototype.getProcurementOrderDetail = function() { var n = this,
                t = this.host.order;
            this.procurementSvc.getPayOrderLiteById(t.id).success(function(i) { if (i.statusLabel = n.procurementPayOrderUtil.getStatusLabelHtml(i), t.currentProductDetails) { var r = {};
                    _.each(t.currentProductDetails, function(n) { r[n.productId] = n.count });
                    _.each(i.procurementOrders[0].procurementOrderItems, function(n) { n.unSettledNum = n.number - n.settledNum;
                        n.currentSettlementNum = r[n.productId] });
                    n.$scope.currentSettlementFreight = t.currentFreightAmount } else _.each(i.procurementOrders[0].procurementOrderItems, function(n) { n.currentSettlementNum = n.unSettledNum = n.number - n.settledNum }), n.$scope.currentSettlementFreight = i.freight - i.settledFreight;
                n.$scope.payOrder = i;
                n.calcItemAmount();
                n.$timeout(function() { n.$scope.updateScrollbar() }, 0, !1) }) }, n.prototype.calcItemAmount = function() { var n = this,
                t;
            this.debouncedCalc && this.$timeout.cancel(this.debouncedCalc);
            t = this.$scope.payOrder;
            this.debouncedCalc = this.$timeout(function() { var i = _.every(t.procurementOrders[0].procurementOrderItems, function(n) { return n.currentSettlementNum === n.unSettledNum }); return i && (n.$scope.currentSettlementFreight = n.round(t.freight - t.settledFreight)), n.procurementSvc.loadSettlementOrderDetails(n._generateDetailCouponSharePostData()).success(function(i) { var r = 0;
                    _.each(t.procurementOrders[0].procurementOrderItems, function(n) { var t = _.find(i.details, function(t) { return t.productId === n.productId });
                        n.orderCouponShare = t.orderCouponShare;
                        n.currentSettlementAmount = t.amount - t.orderCouponShare;
                        n.unSettledNum = n.number - t.settledCount;
                        n.unSettledAmount = t.unsettledAmountWithCoupon;
                        n.totalOrderCouponShare = t.totalOrderCouponShare;
                        n.currentSettlementNum > 0 && (n.price = t.amount / n.currentSettlementNum);
                        r += n.currentSettlementAmount });
                    n.debouncedCalc = null;
                    n.$timeout(function() { n.$scope.currentTotalAmount = r + parseFloat(String(n.$scope.currentSettlementFreight)) }) }), !0 }, 500);
            this.$scope.inStorageProductOnly = _.every(t.procurementOrders[0].procurementOrderItems, function(n) { return n.currentSettlementNum === Math.min(n.inStorageNum, n.unSettledNum) }) }, n.prototype.initProductCodeOptions = function() { var n = this;
            this.inventoryUtil.getProductCodeOptions().then(function(t) { n.$scope.allowInsideCode = t.allowInsideCode }) }, n.prototype.onProductNameClick = function(n, t) { this.eventAggregator.publish(this.eventAggregator.events.ProductSelected, n, t.delegateTarget) }, n.prototype.save = function() { this.$modalInstance.close({ currentPaymentAmount: parseFloat(String(this.$scope.currentTotalAmount)), currentFreightAmount: parseFloat(String(this.$scope.currentSettlementFreight)), currentProductDetails: this._generateCurrentDetails() }) }, n.prototype.onInStorageProductOnlyChange = function() { this.$scope.inStorageProductOnly && (_.each(this.$scope.payOrder.procurementOrders[0].procurementOrderItems, function(n) { n.currentSettlementNum = Math.min(n.inStorageNum, n.unSettledNum) }), this.calcItemAmount()) }, n.prototype._generateCurrentDetails = function() { var n = this.$scope.payOrder; return _(n.procurementOrders[0].procurementOrderItems).map(function(t) { return { procurementPayOrderId: n.id, procurementOrderId: n.procurementOrders[0].id, procurementOrderItemId: t.id, productId: t.productId, count: t.currentSettlementNum } }) }, n.prototype._generateDetailCouponSharePostData = function() { var n = this.$scope.payOrder; return { details: this._generateCurrentDetails(), orderType: this.enums.ProcurementSettlementOrderType.ProcurementPayOrder, referenceOrderId: n.id, referenceOrderNo: n.payOrderNo, freight: this.$scope.currentSettlementFreight } }, n.$inject = ["$scope", "host", "procurementSvc", "procurementPayOrderUtil", "inventoryUtil", "eventAggregator", "$timeout", "loginContext", "aresNotification", "$modalInstance", "enums"], n }();
    supplychainModule.controller("ProcurementSettlementOrderEditDetailCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n() { this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/procurement/dialogs/procurement-settlement-order-edit-view/procurement-settlement-order-edit-view.html";
            this.link = function(n, t) { var i = t.find(".procurement-order-list"),
                    r = function() { i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 } }) },
                    u = function(n, t, r) { if (t) { r.showTooltip = !0; var u = angular.element(n.currentTarget),
                                e = u.find(".iconfont"),
                                f = u.find(".lc-blue-text-des"),
                                o = e.offset().top + 20 + f.height();
                            o > i.height() ? (u.addClass("top"), f.css({ top: "auto", bottom: 30 })) : (u.removeClass("top"), f.css({ top: 30, bottom: "auto" })) } else n.stopPropagation(), r.showTooltip = !1 };
                (function() { n.initTableView = r;
                    n.onToggleTooltip = u })() } } return n.$inject = [], n }();
    supplychainModule.directive("procurementSettlementOrderEditView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p) { var w = this;
            this.$scope = n;
            this.$q = t;
            this.dataDicSvc = i;
            this.$timeout = r;
            this.$sce = u;
            this.enums = f;
            this.procurementSvc = e;
            this.loginContext = o;
            this.officeSvc = s;
            this.officeSelectorUtil = h;
            this.appNav = c;
            this.aresModalShelf = l;
            this.aresNotification = a;
            this.aresConfirmDialog = v;
            this.$state = y;
            this.$modalInstance = p;
            n.isRootGroup = o.isGroup && o.isRootGroup;
            n.checkAll = !1;
            n.officeExpandStatus = {};
            n.isDetailMode = !1;
            this.initBaseData().then(function() { w.search() }) } return n.prototype.search = function() { var r = this,
                n = this.$scope,
                i, t; return n.isSearching = !0, i = this.$q.defer(), t = { startTime: n.searchTimeRange.startDate, endTime: n.searchTimeRange.endDate, supplier: n.selectedDealer.id ? n.selectedDealer.name : "", payOrderStatus: [] }, n.searchCriteria.includeInStorage && t.payOrderStatus.push(this.enums.ProcurementPayOrderStatus.InStorage), n.searchCriteria.includeNotInStorage && t.payOrderStatus.push(this.enums.ProcurementPayOrderStatus.PreInStorage), n.searchCriteria.includePartlyInStorage && t.payOrderStatus.push(this.enums.ProcurementPayOrderStatus.PartInStorage), n.isRootGroup && (t.officeIds = n.searchCriteria.officeIds), this.procurementSvc.searchPreSettlementOrders(t).success(function(t) { n.isSearching = !1;
                _.each(t, function(n) { n.expanded = !0;
                    n.statusHtml = r.getStatusHtml(n);
                    n.settled = n.paymentAmount === n.actualAmount;
                    n.platformTradeNo && (n.platformTradeNoArray = n.platformTradeNo.split(",")) });
                n.allOrders = _.sortBy(t, "officeId");
                r.filterMode().then(function() { return i.resolve() }) }), i.promise }, n.prototype.filterMode = function() { var r = this,
                i = this.$q.defer(),
                n = this.$scope,
                t; return n.procurementOrders = _.filter(n.allOrders, function(t) { return n.isDetailMode ? (t.settlementModeStatus & 2) == 2 : (t.settlementModeStatus & 1) == 1 }), n.supplierGroups = _.map(_.groupBy(n.procurementOrders, "supplierId"), function(n, t) { var i = _.map(_.groupBy(n, "officeId"), function(n, t) { return { orders: n, officeId: parseInt(t), officeName: n[0].officeName, expanded: !0 } }); return { officeGroups: i, supplierId: parseInt(t), supplierName: n[0].supplierName, expanded: !0 } }), t = [], _.each(n.procurementOrders, function(i) { t.push(i);
                i.currentPaymentAmount = n.isDetailMode ? 0 : i.paymentAmount - i.actualAmount;
                i.returnOrders = _.filter(i.returnOrders, function(n) { return n.status !== r.enums.InventoryReturnStatus.Cancelled });
                _.each(i.returnOrders, function(n) { n.supplierId = i.supplierId;
                    n.supplierName = i.supplierName;
                    n.currentPaymentAmount = i.paymentAmount - i.actualAmount;
                    t.push(n) }) }), n.flatOrdersArray = t, n.unsettledCount = _.filter(t, function(n) { return !n.settled }).length, this.$timeout(function() { n.initTableView();
                n.selectedCount = 0;
                n.checkAll = !1;
                n.initTableView();
                i.resolve() }), i.promise }, n.prototype.initBaseData = function() { var t = this,
                n = this.$scope,
                i, r; return n.searchTimeRange = { startDate: moment().startOf("year").format("YYYY-MM-DD"), endDate: moment().format("YYYY-MM-DD") }, n.searchCriteria = { includeInStorage: !0, includeNotInStorage: !1, includePartlyInStorage: !0, officeIds: [] }, i = [], i.push(this.dataDicSvc.dealerDic.loadActive().then(function(t) { var i = [{ id: 0, name: "选择供应商" }];
                _.each(t, function(n) { n.id > 0 && i.push(n) });
                n.dealersSource = i;
                n.selectedDealer = { id: 0 } })), n.isRootGroup && (r = this.$q.defer(), this.officeSvc.getSelfAndChildOfficesByGroupId(this.loginContext.officeId, !1).success(function(i) { t.officeSvc.getGroupProcurementConfigs().success(function(u) { var e = [],
                        o, f;
                    _.each(u, function(n) { n.optionKey === "IsGroupSettlementEnabled" && n.optionValue === "1" && e.push(n.officeId) });
                    o = t.officeSelectorUtil.setId(i);
                    f = _.filter(_.values(t.officeSelectorUtil.flattenToMap(o)), function(n) { return n.officeId === t.loginContext.officeId || n.isGroup || e.indexOf(n.officeId) > -1 });
                    f = _.map(f, function(n) { return n.items = [], n.isGroup && n.officeId !== t.loginContext.officeId && (n.disabled = !0), n });
                    n.officeTreeData = t.officeSelectorUtil.unflatten(f);
                    n.searchCriteria.officeIds = _.pluck(_.filter(f, function(n) { return !n.disabled }), "officeId");
                    r.resolve(!0) }) }), i.push(r.promise)), this.$q.all(i) }, n.prototype.getStatusHtml = function(n) { var t; switch (n.status) {
                case this.enums.ProcurementPayOrderStatus.PreInStorage:
                    t = '<span class="enyo-text-warning">待入库<\/span>'; break;
                case this.enums.ProcurementPayOrderStatus.PartInStorage:
                    t = '<span class="enyo-text-warning">部分入库<\/span>'; break;
                case this.enums.ProcurementPayOrderStatus.InStorage:
                    t = '<span class="enyo-text-success">已完成<\/span>' } return this.$sce.trustAsHtml(t) }, n.prototype.save = function() { var n = this,
                t = this.$q.defer(),
                i = {},
                r, u; return this.$scope.isDetailMode && (r = _.find(this.$scope.flatOrdersArray, function(n) { return n.checked && n.payOrderId && (!n.currentProductDetails || n.currentProductDetails.length === 0 && n.currentFreightAmount === 0 || _.every(n.currentProductDetails, function(n) { return n.count === 0 })) }), r) ? (this.aresNotification.error("请设置采购单【" + r.payOrderNo + "】的支付明细"), t.reject({ name: "AresBusinessException", message: "请设置采购单【" + r.payOrderNo + "】的支付明细" }), t.promise) : (_.each(this.$scope.flatOrdersArray, function(t) { if (t.checked)
                    if (i[t.supplierId] || (i[t.supplierId] = { supplierId: t.supplierId, supplierName: t.supplierName, items: [], officeId: n.loginContext.officeId, settlementMode: n.$scope.isDetailMode ? n.enums.ProcurementSettlementMode.ByDetail : n.enums.ProcurementSettlementMode.ByOrder }), t.payOrderId) { var r = { referenceOrderId: t.payOrderId, referenceOrderNo: t.payOrderNo, orderType: 1 };
                        n.$scope.isDetailMode && _.extend(r, { amount: t.currentPaymentAmount, freight: t.currentFreightAmount, details: t.currentProductDetails });
                        i[t.supplierId].items.push(r) } else t.returnOrderId && i[t.supplierId].items.push({ referenceOrderId: t.returnOrderId, referenceOrderNo: t.returnOrderNo, orderType: 2 }) }), u = _.values(i), this.procurementSvc.createSettlementOrders(u).success(function(n) { t.resolve({ response: n, postDateLength: u.length }) }).error(function(n) { t.reject(n) }), t.promise) }, n.prototype.goToMallOrderDetail = function(n) { var t = { action: this.enums.ProcurementMallAction.OrderDetail, orderSn: n };
            this.appNav.goToState("mallCenter", t) }, n.prototype.goToMallServiceDetai = function(n) { var t = { action: this.enums.ProcurementMallAction.ServiceOrder, serviceSn: n };
            this.appNav.goToState("mallCenter", t) }, n.prototype.onToggleOfficeExpand = function(n) { var t = this.$scope;
            n.expanded = !n.expanded;
            this.$timeout(function() { t.initTableView() }, 0, !1) }, n.prototype.onToggleSupplierExpand = function(n) { var t = this.$scope;
            n.expanded = !n.expanded;
            this.$timeout(function() { t.initTableView() }, 0, !1) }, n.prototype.onOfficeSelect = function(n) { this.$scope.searchCriteria.officeIds = _.pluck(n, "officeId");
            this.search() }, n.prototype.showProcurementOrderDetail = function(n) { this.aresModalShelf.open({ title: "采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-detail-view><\/procurement-order-detail-view>", controller: "ProcurementOrderDetailCtrl", resolve: { host: function() { return { payOrderId: n.payOrderId, disableAction: !0 } } }, needActive: !0 }) }, n.prototype.countSelected = function() { var n = this.$scope,
                t;
            n.checkAll ? n.selectedCount = n.unsettledCount : (t = _.filter(n.flatOrdersArray, function(n) { return n.checked }), n.selectedCount = t.length) }, n.prototype.onCheckAllChange = function() { var n = this.$scope;
            _.each(n.procurementOrders, function(t) { t.settled || (t.checked = n.checkAll);
                _.each(t.returnOrders, function(t) { t.checked = n.checkAll }) });
            this.countSelected() }, n.prototype.onProcurementOrderCheckChange = function(n) {
            (n.supplierType === this.enums.OrganizationType.LinkedCare || n.supplierType === this.enums.OrganizationType.MallDealer) && _.each(n.returnOrders, function(t) { t.checked = n.checked });
            this.onCheckChange() }, n.prototype.onCheckChange = function() { var n = this.$scope,
                t = _.some(n.flatOrdersArray, function(n) { return !n.settled && !n.checked });
            n.checkAll = !t;
            this.countSelected() }, n.prototype.onSave = function() { var n = this,
                t = this.$scope; if (!t.selectedCount) { this.aresConfirmDialog.error({ message: "请选择采购单或退货单" }); return } this.save().then(function(i) { var r = i.response,
                    s = i.postDateLength,
                    u, f, e, o;
                r.code === "A0000" ? (u = n.$sce.trustAsHtml('已新增 <span class="enyo-text-warning">' + s + "<\/span> 个对账单<br>是否立即去结算？"), n.aresConfirmDialog.warn({ message: u, onConfirm: function() { n.$state.go("supplychain.procurement.settlementOrder");
                        n.$modalInstance.close() }, onCancel: function() { n.$modalInstance.close() } })) : r.code === "A0001" && (r.failedList && r.failedList.length > 0 ? (u = "<p>对账单新建失败，具体原因：<\/p>", _.each(r.failedList, function(n) { u += n.orderSn + "，" + n.msg + "<br>" }), n.aresConfirmDialog.warn({ message: n.$sce.trustAsHtml(u) }), f = [], _.each(r.failedList, function(n) { var i = _.find(t.procurementOrders, function(t) { return angular.isArray(t.platformTradeNoArray) && t.platformTradeNoArray.indexOf(n.orderSn) > -1 });
                    i && f.push(i.id) }), e = _.filter(t.procurementOrders, function(n) { return n.checked && f.indexOf(n.id) < 0 }), o = _.pluck(e, "id"), n.search().then(function() { _.each(t.procurementOrders, function(t) { if (o.indexOf(t.id) > -1) { t.checked = !0;
                            n.onProcurementOrderCheckChange(t) } }) })) : n.aresConfirmDialog.warn({ message: r.msg })) }, function(t) { t && t.name === "AresBusinessException" || n.aresNotification.error(t.message || t.msg || "创建对账单失败！") }) }, n.prototype.onTimeRangeChanged = function(n) { this.$scope.searchTimeRange.startDate = n.startDate;
            this.$scope.searchTimeRange.endDate = n.endDate;
            this.search() }, n.prototype.onSupplierGroupCheckChange = function(n) { _.each(n.officeGroups, function(t) { t.checked = n.checked;
                _.each(t.orders, function(t) { t.checked = t.settled ? !1 : n.checked;
                    _.each(t.returnOrders, function(t) { t.checked = n.checked }) }) });
            this.onCheckChange() }, n.prototype.onOfficeGroupCheckChange = function(n) { _.each(n.orders, function(t) { t.checked = t.settled ? !1 : n.checked;
                _.each(t.returnOrders, function(t) { t.checked = n.checked }) });
            this.onCheckChange() }, n.prototype.setOrderItems = function(n) { var t = this,
                i = this.aresModalShelf.open({ title: "选择结算明细", template: "<procurement-settlement-order-edit-detail-view><\/procurement-settlement-order-edit-detail-view>", controller: "ProcurementSettlementOrderEditDetailCtrl", needActive: !0, resolve: { host: function() { return { order: n } } } });
            i.result.then(function(i) { i && (n.checked = !0, _.extend(n, i), t.onCheckChange()) }) }, n.$inject = ["$scope", "$q", "dataDicSvc", "$timeout", "$sce", "enums", "procurementSvc", "loginContext", "officeSvc", "officeSelectorUtil", "appNav", "aresModalShelf", "aresNotification", "aresConfirmDialog", "$state", "$modalInstance"], n }();
    supplychainModule.controller("ProcurementSettlementOrderEditCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("procurementSettlementOrderListView", ["$timeout", "$window", "aresModalShelf", "aresConfirmDialog", "aresNotification", "enums", "appNav", function(n, t, i, r, u, f, e) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/procurement/dialogs/procurement-settlement-order-list/procurement-settlement-order-list-view.html", controller: "ProcurementSettlementOrderListCtrl", link: function(o, s) { var h, c, l = function() { h = s.find(".left-side-container .table-main-content"); var n = angular.element(t).height() - 255 - (window.Ares3 ? 25 : 0);
                    o.showSearchForm && (n -= 120);
                    h.height(n);
                    h.data("mCustomScrollbarIndex") ? h.mCustomScrollbar("update") : h.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) },
                a = function() { c = s.find(".right-side-container .table-main-content");
                    c.height(angular.element(t).height() - 296 - (window.Ares3 ? 25 : 0));
                    c.data("mCustomScrollbarIndex") ? c.mCustomScrollbar("update") : c.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) },
                y = function(t, i) { o.activeIndex = i;
                    o.getSettlementOrderDetail(t).then(function() { v();
                        n(function() { a() }, 0, !1) }) },
                p = function(n) { var t = i.open({ title: "采购单", titleIconClass: "iconfont icon-caigouoff", template: "<procurement-order-detail-view><\/procurement-order-detail-view>", controller: "ProcurementOrderDetailCtrl", resolve: { host: function() { return { payOrderId: n } } } }) },
                w = function() { o.showSearchForm = !o.showSearchForm;
                    n(function() { l() }, 0, !1) },
                b = function(n) { n.keyCode === 13 && o.search() },
                k = function(n) { o.state = n;
                    o.searchNo = "";
                    o.selectedDealer = { id: 0 };
                    o.currentSettlementOrder = null;
                    o.searchTimeRange = n === 0 ? { startDate: "", endDate: "" } : o.defaultSearchTimeRange;
                    o.search() },
                d = function() { o.search() },
                g = function(n) { r.warn({ message: "确定要作废当前对账单吗？", showCancelBtn: !0 }).then(function() { o.cancelOrder(n.orderNo).then(function() { u.success("作废成功");
                            o.search() }, function() { u.error("作废失败") }) }) },
                nt = function() { var t = o.currentSettlementOrder,
                        i, n; if (t.settlementMode === f.ProcurementSettlementMode.ByOrder) { if (n = _.find(t.items, function(n) { return Math.abs(n.settledAmount) + Math.abs(parseFloat(n.postAmount)) > Math.abs(n.totalAmount) }), n) return n.orderType === f.ProcurementSettlementOrderType.ProcurementPayOrder && (i = "采购单【"), n.orderType === f.ProcurementSettlementOrderType.ProcurementReturnOrder && (i = "退货单【"), i += n.referenceOrderNo + "】的支付金额不能大于" + Math.abs(n.totalAmount - n.settledAmount).toFixed(2), u.error(i), !1;
                        n = _.find(t.items, function(n) { return parseFloat(n.postAmount) === 0 });
                        _.each(t.items, function(n) { n.amount = n.orderType === f.ProcurementSettlementOrderType.ProcurementReturnOrder ? 0 - n.postAmount : n.postAmount }) } o.approveOrder(t).then(function() { u.success("操作成功");
                        o.search() }, function() { u.error("操作失败") }) },
                v = function() { var n = 0;
                    _.each(o.currentSettlementOrder.items, function(t) { o.currentSettlementOrder.settlementMode === f.ProcurementSettlementMode.ByOrder ? t.orderType === 1 ? n += parseFloat(t.postAmount) : n -= parseFloat(t.postAmount) : n += t.amount + t.freight - t.orderCouponShare });
                    o.currentSettlementOrder.totalActualAmount = n },
                tt = function(n) { var t = { action: f.ProcurementMallAction.Pay, settlementOrderNo: n };
                    e.goToState("mallCenter", t) },
                it = function(n) { n.expanded = !n.expanded;
                    _.each(n.items, function(t) { t.hidden = !n.expanded }) },
                rt = function(n) { var t = { action: f.ProcurementMallAction.OrderDetail, orderSn: n };
                    e.goToState("mallCenter", t) },
                ut = function(n) { var t = { action: f.ProcurementMallAction.ServiceOrder, serviceSn: n };
                    e.goToState("mallCenter", t) };
            (function() { o.state = 0;
                o.officeExpandStatus = {};
                o.showSearchForm = !1;
                o.showDetail = y;
                o.showProcurementOrderDetail = p;
                o.onToggleSearchForm = w;
                o.onSearchNoKeyUp = b;
                o.onSwitchState = k;
                o.onSearchTimeRangeChanged = d;
                o.onCancel = g;
                o.onApproveOrder = nt;
                o.onAmountChange = v;
                o.initListView = l;
                o.initMainView = a;
                o.goToPay = tt;
                o.onToggleOfficeExpand = it;
                o.goToMallOrderDetail = rt;
                o.goToMallServiceDetail = ut;
                o.isAres3 = window.Ares3;
                o.initBaseData().then(function() { o.search().then(function() { n(function() { l();
                            a() }, 0, !1) }) }) })() } } }]);
supplychainModule.controller("ProcurementSettlementOrderListCtrl", ["$scope", "$q", "$timeout", "dataDicSvc", "$sce", "enums", "procurementSvc", "loginContext", "aresDialog", "excelExportUtil", "officeSvc", "reportUtil", "aresModalShelf", "aresNotification", "appNav", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y) { var w = function() { var r = t.defer(),
                u = { startTime: n.searchTimeRange.startDate, endTime: n.searchTimeRange.endDate, supplier: n.selectedDealer.id ? n.selectedDealer.name : "", searchNo: n.searchNo, isSettled: n.state !== 0, pageSize: n.page.pageSize, pageIndex: n.page.pageIndex }; return e.searchSettlementOrders(u).success(function(t) { if (n.page.totalCount = t.totalCount, n.page.pageCount = t.pageCount, n.pageData = t, n.pageData.items.length > 0) { var u = n.pageData.items[0];
                    p(u).then(function() { n.activeIndex = 0;
                        n.onAmountChange();
                        i(function() { n.initMainView() }, 0, !1) }) } else n.currentSettlementOrder = null, n.activeIndex = -1;
                i(function() { n.initListView();
                    n.initMainView() }, 0, !1);
                r.resolve() }), r.promise },
        b = function() { var u = l.getDefaultTimeSpan(),
                i; return n.defaultSearchTimeRange = { startDate: u.startTime, endDate: u.endTime }, n.searchTimeRange = { startDate: "", endDate: "" }, i = [], i.push(r.dealerDic.loadActive().then(function(t) { n.dealersSource = [{ id: 0, name: "全部供应商" }].concat(t);
                n.selectedDealer = { id: 0 } })), t.all(i) },
        k = function(n) { var t = ""; switch (n.status) {
                case f.ProcurementSettleStatus.Pending:
                    t = '<div class="label label-danger">未结算<\/div>'; break;
                case f.ProcurementSettleStatus.Settling:
                    t = '<div class="label label-warning">结算中<\/div>'; break;
                case f.ProcurementSettleStatus.Settled:
                    t = '<div class="label label-success">已结算<\/div>' } n.statusHtml = u.trustAsHtml(t) },
        d = function(n) { var t = ""; switch (n.status) {
                case f.ProcurementSettleItemStatus.Pending:
                    t = '<span class="enyo-text-danger">未核对<\/span>'; break;
                case f.ProcurementSettleItemStatus.Checked:
                    t = '<span class="enyo-text-warning">已核对<\/span>'; break;
                case f.ProcurementSettleItemStatus.Settled:
                    t = '<span class="enyo-text-success">已结算<\/span>' } n.statusHtml = u.trustAsHtml(t) },
        ot = function(n) { var t = ""; switch (n.status) {
                case f.ProcurementSettleItemStatus.Pending:
                    t = "未核对"; break;
                case f.ProcurementSettleItemStatus.Checked:
                    t = "已核对"; break;
                case f.ProcurementSettleItemStatus.Settled:
                    t = "已结算" } return t },
        g = function(n) { return e.cancelSettlementOrder(n) },
        nt = function(n) { return e.approveSettlementOrder(n) },
        tt = function() { var t = _.pluck(n.currentSettlementOrder.officeGroups, "officeId");
            c.getOfficeInvoices(t).success(function(t) { _.each(n.currentSettlementOrder.officeGroups, function(n) { var i = _.find(t, function(t) { return t.officeId == n.officeId });
                    i && (n.invoiceData = "开票信息：发票抬头：" + i.taxTitle + " 纳税人识别号：" + i.taxNo + " 开户行：" + i.bankName + " 银行帐号：" + i.account + " 地址：" + i.province + i.city + i.district + i.address + " 电话：" + i.phoneNumber) });
                rt() }) },
        it = function(n) { if (n.supplierType === f.OrganizationType.NormalDealer) n.canCancel = !0;
            else if (n.status === f.ProcurementSettleStatus.Settled) n.canCancel = !1;
            else { var t = _.any(n.items, function(n) { return n.status === f.ProcurementSettleItemStatus.Settled });
                n.canCancel = !t } },
        rt = function() { var a = h.generateColumnSettings,
                u = h.Row,
                v = h.MainHeaderRow,
                t = h.HeaderCell,
                y = h.LabelCell,
                o = h.BoldCell,
                i = h.RegularCell,
                e = h.CenterCell,
                s = h.NumberCell,
                f = h.PriceCell,
                p = a([40, 75, 135, 135, 65, 135, 65, 80, 60, 60, 60, 80, 60, 60]),
                r = [],
                w = new v("对账单", 14),
                c, l;
            r.push(w);
            r.push(new u([new t("供应商：", 2, "left"), new i(n.currentSettlementOrder.supplierName, 4), new t("对账单号：", 1, "left"), new i(n.currentSettlementOrder.orderNo, 3), new t("单据日期：", 1, "left"), new i(moment(n.currentSettlementOrder.orderDate).format("YYYY-MM-DD"), 3)]));
            r.push(new u([new t("序号"), new t("下单日期"), new t("采购订单/退货单号"), new t("商城订单/服务单号"), new t("单据类型"), new t("名称"), new t("品牌"), new t("规格"), new t("单位"), new t("单价"), new t("数量"), new t("金额"), new t("折扣优惠"), new t("小计")], 30));
            _.each(n.currentSettlementOrder.officeGroups, function(t) { r.push(new u([new o("下单机构：" + t.items[0].referenceOrderOfficeName, 9), new o(n.currentSettlementOrder.supplierType !== 0 ? "商城核对单号：" + t.items[0].platformSettlementOrderNo : "", 5)]));
                t.invoiceData && r.push(new u([new o(t.invoiceData, 14)]));
                t.items = _.sortBy(t.items, "orderType"); var l = 1,
                    h = 0,
                    c = 0;
                _.each(t.items, function(t) { _.each(t.details, function(o) { r.push(new u([new e(l), new e(moment(t.referenceOrderDate).format("YYYY-MM-DD")), new e(t.referenceOrderNo), new e(n.currentSettlementOrder.supplierType > 0 ? o.orderNo : ""), new e(t.orderType == 1 ? "进货" : "退货"), new i(o.name), new i(o.producer), new i(o.specification), new i(o.unit), o.name === "运费" ? i("") : new f(parseFloat((o.amount / o.count).toFixed(2))), o.name === "运费" ? i("") : new s(o.count), new f(o.amount), o.name === "运费" ? i("") : new f(0 - o.orderCouponShare), new f(o.amount - o.orderCouponShare)]));
                        h += o.amount || 0;
                        c += o.orderCouponShare || 0;
                        l++ }) });
                r.push(new u([new y("合计", 10), new s(t.totalCount), new f(h), new f(0 - c), new f(h - c)]));
                r.push(new u([new i("", 14)])) });
            c = { sheets: [{ title: "供应商对账单" + n.currentSettlementOrder.orderNo, columns: p, rows: r }] };
            l = new kendo.ooxml.Workbook(c);
            kendo.saveAs({ dataURI: l.toDataURL(), fileName: "供应商对账单" + n.currentSettlementOrder.orderNo + ".xlsx" }) },
        p = function(i) { var r = t.defer(); return e.getSettlementOrderDetail(i.orderNo).success(function(t) { var i = t[0],
                    e, u;
                it(i);
                k(i);
                e = _.groupBy(i.items, "referenceOrderOfficeId");
                u = [];
                _.each(e, function(n, t) { n = _.sortBy(n, "referenceOrderDate"); var r = 0,
                        e = 0;
                    _.each(n, function(n) { n.postAmount = Math.abs(n.totalAmount - n.settledAmount - n.amount).toFixed(2);
                        d(n);
                        (i.supplierType === f.OrganizationType.LinkedCare || i.supplierType === f.OrganizationType.MallDealer) && (n.platformTradeNoArray = n.platformTradeNo.split(","));
                        _.each(n.details, function(n) { r += n.count });
                        e += n.totalAmount });
                    u.push({ items: n, expanded: !0, totalCount: r, totalAmount: e, officeId: t, canPay: moment(i.orderDate).isAfter(moment("2019-03-01")) && n[0].status != 2 && n[0].platformSettlementOrderNo }) });
                i.officeGroups = u;
                i.canPay = moment(i.orderDate).isAfter(moment("2019-03-01")) && i.status != 2 && i.supplierType !== 0 && i.totalAmount > 0 && _.uniq(_.pluck(i.items, "platformSettlementOrderNo")).length === 1;
                n.currentSettlementOrder = i;
                i.hasInvoice = i.invoices && i.invoices.length > 0;
                r.resolve() }), r.promise },
        ut = function() { var t = a.open({ title: "供应商对账单 - " + n.currentSettlementOrder.orderNo + " - 关联发票", template: "<procurement-settlement-invoice-list-view><\/procurement-settlement-invoice-list-view>", controller: "ProcurementSettlementInvoiceListCtrl", resolve: { host: function() { return { settlementOrder: angular.copy(n.currentSettlementOrder) } } }, confirmClose: !0 });
            t.result.then(function() { p(n.currentSettlementOrder).then(function() { n.onAmountChange() }) }) },
        ft = function() { s.confirm("提示", "发起申请后，该对账单将不可变更撤销，您确定要申请开票吗").then(function() { e.confirmStatement(n.currentSettlementOrder.items[0].platformSettlementOrderNo).success(function(n) { n && n.code === "A0000" ? v.success("申请成功") : n && n.code === "A0003" ? s.confirm("提示", "您还未配置默认开票地址，需要跳转到商城去配置。").then(function() { et() }) : n ? v.error(n.msg || "操作失败") : v.error("操作失败") }) }) },
        et = function() { var n = { action: f.ProcurementMallAction.Invoice };
            y.goToState("mallCenter", n) };
    (function() { n.page = { pageSize: 20, pageIndex: 1 };
        n.isRootGroup = o.isGroup && o.isRootGroup;
        n.initBaseData = b;
        n.search = w;
        n.cancelOrder = g;
        n.approveOrder = nt;
        n.exportExcel = tt;
        n.getSettlementOrderDetail = p;
        n.showInvoiceModal = ut;
        n.applyInvoice = ft })() }]);
supplychainModule.directive("productCategoryEditView", ["$log", "$timeout", "$window", function(n, t, i) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-category/product-category-edit-view.html", link: function(n, r) { var u = function(t) { n.parentNode = t },
                f = angular.element(i).height() / 2 - 60;
            (function() { t(function() { Ares.centerModal(r.closest(".modal-dialog")) }, 100);
                n.treeDropDownHeight = f;
                n.onParentNodeChange = u })() } } }]);
supplychainModule.directive("productCategoryManagementView", ["$log", "$window", "$timeout", "$modal", "aresNotification", function(n, t, i, r, u) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-category/product-category-management-view.html", link: function(n, t) { var h = function() { t.parents(".modal-content").css("float", "right").css("width", "640px");
                    t.find(".panel").height($(window).height() - 102).find(".panel-content").height($(window).height() - 142) },
                c = function() { t.on("focus", ".list-input-group-input", function() { $(this).parent(".list-input-group").addClass("focused").removeClass("warning") }).on("blur", ".list-input-group-input", function() { $(this).val().trim() ? $(this).siblings(".list-input-btn").click() : $(this).parent(".list-input-group").removeClass("focused").addClass("warning") }).on("click", ".list-new-btn", function() { var n = $(this);
                        n.hasClass("disabled") || (n.siblings(".list-input-group").show().find("input").show().focus(), n.addClass("disabled")) }).on("keyup", ".list-input-group-input", function(n) { n.keyCode === 13 && $(this).siblings(".list-input-btn").click() }) },
                e = !1,
                l = function(i, r) { var o, h, f, c; if (!e) { if (e = !0, o = n.newCategoryNames[i], h = $(r.target).closest(".list-input-group"), !o) { h.addClass("warning"); return } f = { id: 0, name: o };
                        c = function(t) { if (!n.selectedNodes[t].items) return 0; var i = _.max(n.selectedNodes[t].items, function(n) { return n.showOrder }); return i + 1 }; switch (i) {
                            case "first":
                                f.parentId = 0;
                                f.showOrder = n.treeData.length + 1; break;
                            case "second":
                                f.parentId = n.selectedNodes.first.id;
                                f.showOrder = c("first"); break;
                            case "third":
                                f.parentId = n.selectedNodes.second.id;
                                f.showOrder = c("second") } n.saveNewCategory(f).then(function(t) { u.success("新建成功");
                            s();
                            n.passedInSelected = t.data;
                            n.loadTreeData();
                            h.siblings(".list-new-btn").removeClass("disabled") }).catch(function() { t.find(".list-input-group").addClass("warning") }).finally(function() { e = !1 }) } },
                s = function() { n.newCategoryNames = { first: "", second: "", third: "" };
                    t.find(".list-input-group").removeClass("warning").removeClass("focused").hide() },
                a = function(t, i, r) { $(t.target).closest(".panel").siblings(".panel").find(".list-input-group").removeClass("warning").removeClass("focused").hide().end().find(".list-new-btn").removeClass("disabled"); switch (i) {
                        case "first":
                            n.selectedNodes.first = r;
                            n.selectedNodes.second = null;
                            n.selectedNodes.third = null;
                            n.secondLevelNodes = r.items || [];
                            n.thirdLevelNodes = [];
                            f(i, r); break;
                        case "second":
                            n.selectedNodes.second = r;
                            n.selectedNodes.third = null;
                            n.thirdLevelNodes = r.items || [];
                            f(i, r); break;
                        case "third":
                            n.selectedNodes.third = r;
                            f(i, r) } },
                v = function(t) { var i = n.selectedNodes[t]; if (i) { var u = n.getUpperTreeById(i.id),
                            f = i.parentId === 0 ? null : n.nodeMap[i.parentId],
                            e = r.open({ animation: !0, backdrop: "static", template: "<product-category-edit-view><\/product-category-edit-view>", controller: "ProductCategoryEditCtrl", windowClass: "product-category-edit-modal-wrapper", size: "md", resolve: { host: function() { return { currentNode: i, parentNode: f, currentLevel: t, upperTree: u } } } });
                        e.result.then(function(t) { n.passedInSelected = t;
                            n.loadTreeData();
                            n.clearSelected() }) } },
                f = function(t, i) { var r, u;
                    r = i.parentId === 0 ? n.treeData : n.nodeMap[i.parentId].items;
                    u = _.findIndex(r, function(n) { return n.id === i.id });
                    n.moveBtnStatus[t].up = u > 0;
                    n.moveBtnStatus[t].down = u < r.length - 1 },
                o, y = function(t, r) { var e; if (o && i.cancel(o), e = n.selectedNodes[t], e) { var s = e.parentId === 0 ? n.treeData : n.nodeMap[e.parentId].items,
                            h = _.findIndex(s, function(n) { return n.id === e.id }),
                            c = r === "up" ? h - 1 : h + 1;
                        s.splice(h, 1);
                        s.splice(c, 0, e);
                        f(t, e);
                        o = i(function() { n.saveShowOrder(s).then(function() { u.success("排序保存成功") }, function() { u.error("排序保存失败") }) }, 1e3) } },
                p = function(t) { var i = n.selectedNodes[t]; if (i) { if (_.isArray(i.items) && i.items.length > 0) { u.error("当前分类有子分类，无法删除"); return } n.deleteCategory(i).then(function() { u.success("删除成功"); var r = i.parentId === 0 ? n.treeData : n.nodeMap[i.parentId].items,
                                f = _.findIndex(r, function(n) { return n.id === i.id });
                            r.splice(f, 1);
                            n.selectedNodes[t] = null }, function() {}) } };
            (function() { h();
                c();
                n.moveBtnStatus = { first: { up: !1, down: !1 }, second: { up: !1, down: !1 }, third: { up: !1, down: !1 } };
                s();
                n.onSaveNewCategory = l;
                n.onCategorySelect = a;
                n.openEditModal = v;
                n.moveNode = y;
                n.onDeleteSelectedNode = p;
                n.updateMoveBtnStatus = f })() } } }]);
supplychainModule.directive("productCategorySelectModalView", ["$timeout", "$window", function(n, t) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-category/product-category-select-modal-view.html", link: function(i, r) { var e = function() { var e = r.find(".tree-container"),
                        f;
                    f = i.parentModalHeight ? i.parentModalHeight - 180 : angular.element(t).height() - 220;
                    i.mode === "simple" && (f = f + 70);
                    e.height(f);
                    u();
                    n(function() { Ares.centerModal(r.closest(".modal-dialog")) }, 5) },
                u = function() { var n = r.find(".tree-container");
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) },
                f = function(n) { if (!n || !_.isArray(n.breadcrumb)) return " "; var t = "";
                    _.each(n.breadcrumb, function(i, r) { t += r !== n.breadcrumb.length - 1 ? '<span class="breadcrumb-item">' + i + "<\/span> - " : '<span class="breadcrumb-highlight">' + i + "<\/span>" });
                    i.currentBreadcrumb = t },
                o = function(n) { i.mode === "full" && f(n) },
                s = function(t) { i.mode === "full" ? f(t) : (i.selectedCategory = t, n(function() { i.confirm() })) },
                h = function(n) { n === "expand" ? i.treeInstance.expand(r.find(".k-item")) : n === "collapse" && i.treeInstance.collapse(r.find(".k-item"));
                    i.btnCollapse = !i.btnCollapse };
            (function() { e();
                i.updateScroll = u;
                i.onSelect = s;
                i.onChange = o;
                i.currentBreadcrumb = "";
                i.btnCollapse = !0;
                i.treeInstance = null;
                i.toggleAll = h })() } } }]);
supplychainModule.directive("productBasicDataManagementView", ["$timeout", "$window", "aresNotification", "officeUtil", function(n, t, i, r) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-mgmt/product-basic-data-management-view.html", controller: "ProductBasicDataManagementCtrl", link: function(u, f) { var e = function() { r.isRootGroup().then(function(n) { var i = angular.element(t).height();
                        f.find(".data-panel-body").each(function() { var t = angular.element(this),
                                i = n ? t.siblings(".data-panel-footer").height() : 0;
                            t.css("max-height", 500 - i + "px");
                            t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar({ scrollButtons: { enable: !1 }, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) }) }) },
                h = function() { f.on("blur", "input.list-input-group-input", function() { $(this).val().trim() ? $(this).siblings(".list-input-btn").click() : $(this).parent(".list-input-group").removeClass("focused").addClass("warning") }).on("keyup", ".list-input-group-input", function(n) { n.keyCode === 13 && ($(this).val().trim() ? $(this).siblings(".list-input-btn").click() : $(this).parent(".list-input-group").removeClass("focused").addClass("warning")) }) },
                c = function() { f.find('[data-toggle="tooltip"]').tooltip() },
                l = function(n, t) { var i = angular.element(t.target);
                    i.siblings(".list-input-group").removeClass("warning").addClass("focused").show().find("input").focus();
                    i.addClass("disabled");
                    e() },
                o = !1,
                a = function(n, t) { if (!o) { o = !0; var r = u.newItemName[n];
                        u.addItem(n, r).then(function() { u.newItemName[n] = null;
                            i.success("保存成功"); var r = angular.element(t.target).closest(".list-input-group").removeClass("warning").removeClass("focused").hide();
                            r.siblings(".list-new-btn").removeClass("disabled");
                            e() }).catch(function(n) { n.name === "SystemItemNameNotUniqueException" ? i.error("已经有其他项目使用此名称，请更换新名称！") : n.msg && i.error(n.msg) }).finally(function() { o = !1 }) } },
                v = function(n) { var i = u.selectedItem[n],
                        t = _.findIndex(u.dataItems[n], function(n) { return n.id === i.id });
                    u.movableStatus[n] = { up: t !== 0, down: t !== u.dataItems[n].length - 1 } },
                y = function(n, t) { u.selectedItem[n] = t;
                    v(n) },
                s, p = function(t, i) { s && n.cancel(s); var e = u.selectedItem[t],
                        r = _.findIndex(u.dataItems[t], function(n) { return n.id === e.id }),
                        f = i === "up" ? r - 1 : r + 1;
                    u.movableStatus[t] = { up: f !== 0, down: f !== u.dataItems[t].length - 1 };
                    u.dataItems[t].splice(r, 1);
                    u.dataItems[t].splice(f, 0, e);
                    _.each(u.dataItems[t], function(n, t) { n.displayOrder = t + 1 });
                    s = n(function() { u.updateList(t) }, 2e3) },
                w = function() { e();
                    h();
                    n(function() { c() }) };
            (function() { u.initView = e;
                u.onNewBtnClick = l;
                u.onSaveNewItem = a;
                u.onListItemSelected = y;
                u.move = p;
                u.movableStatus = {};
                u.isAres3 = window.Ares3;
                w() })() } } }]);
supplychainModule.directive("productMgmtHomeView", ["eventAggregator", "tenantSvc", "aresModalShelf", function(n, t, i) { "use strict"; return { restrict: "E", templateUrl: "/app/supplychain/views/product-mgmt/product-mgmt-home-view.html", link: function(r) { var u = function() { var n = i.open({ title: "物品信息设置", template: "<product-basic-data-management-view><\/product-basic-data-management-view>", customWidth: "1000px" }) },
                f = function() { var n = [];
                    window.Ares3 && n.push(new Ares.TabCommand("设置", u, "lc-btn lc-btn-primary", 0, { permissionCode: "product.productInfo" }));
                    t.GetTenantIsCustomizeOpen().then(function(t) { t.data || n.push(new Ares.TabCommand('<i class="iconfont icon-wenhao"><\/i>帮助', e, "lc-btn lc-btn-cyan lc-btn-icon lc-btn-icon-narrow", 0)) }).then(function() { r.commands = n }) },
                e = function() { n.publish(n.events.HelpSlideToggled, {}, "ProductMgmtHome") };
            (function() { f() })() } } }]);
supplychainModule.directive("productSystemItemView", ["$log", "$q", "$timeout", "$window", "officeUtil", function(n, t, i, r, u) { return { restrict: "E", templateUrl: "/app/supplychain/views/product-mgmt/product-system-item-view.html", controller: "ProductSystemItemCtrl", scope: { key: "=" }, link: function(n, t) { var o = Ares.kendoGridUtil(r, n),
                f = null,
                s = function() { var i = this.dataSource.data(),
                        n;
                    t.find("#systemitemList table tbody tr").each(function(n, t) { var r = i[n];
                        r.isDefault && $("td.cell-command", t).children().remove() });
                    n = this.items();
                    $(n).each(function() { var n = $(this).index() + 1,
                            t = $(this).find(".row-number");
                        $(t).html(n) }) },
                h = function() { if (n.systemItems) { var u = $(t).find("#systemitemList"),
                            r = [{ title: "序号", sortable: !1, width: "50px", template: "<span class='row-number'><\/span>", headerAttributes: { style: "text-align: center; font-size: 14px; font-weight: bolder;" }, attributes: { style: "height: 33px;" } }, { field: "itemName", title: "名称", width: "300px", headerAttributes: { style: "text-align: center; font-size: 14px; font-weight: bolder;" } }];
                        n.isRootGroup && r.push({ template: o.commandTemplate, title: "", width: "150px", attributes: { "class": "cell-command" } });
                        f = u.kendoGrid({ dataSource: n.systemItems, scrollable: !1, sortable: !1, selectable: "single", dataBound: s, columns: r, change: function() { var t = f.select();
                                i(function() { n.selectedRowIndex = $("tr", f.tbody).index(t) }) } }).data("kendoGrid") } },
                e = function(i) { if (f ? f.dataSource.data(n.systemItems) : u.isRootGroup().then(function(t) { n.isRootGroup = t;
                            h() }), i) { var r = f.dataSource,
                            e = r.get(i),
                            s = r.indexOf(e),
                            o = t.find("#systemitemList").find("tbody>tr[data-uid=" + e.uid + "]");
                        f.select(o) } },
                c = function(t) { if (n.selectedRowIndex != null) { n.isDisableMoveBtn = !0; var i = angular.copy(n.systemItems[n.selectedRowIndex]),
                            r = angular.copy(n.systemItems[n.selectedRowIndex + t]),
                            u = angular.copy(i);
                        i.displayOrder = r.displayOrder;
                        r.displayOrder = u.displayOrder;
                        n.systemItems[n.selectedRowIndex] = r;
                        n.systemItems[n.selectedRowIndex + t] = i;
                        n.selectedRowIndex = n.selectedRowIndex + t;
                        e(i.id);
                        n.updateList() } },
                l = [{ text: "修改", action: "update", icon: "glyphicon-pencil" }, { text: "删除", action: "delete", icon: "glyphicon-remove" }, ],
                a = function(t, i, r) { var u = _.find(n.systemItems, { id: r * 1 }); switch (i) {
                        case "update":
                            n.editSystemItem(u); break;
                        case "delete":
                            n.deleteSystemItem(u) } };
            (function() { n.selectedRowIndex = null;
                n.move = c;
                n.commands = l;
                n.onCommandClick = a;
                n.isDisableMoveBtn = !1;
                n.$watch("systemItems", function() { e() }) })() } } }]);
supplychainModule.directive("inventoryProductUnityListView", ["$log", "$timeout", "$window", "$modal", "permissionProvider", "loginContext", "aresSlidePanel", "aresNotification", "eventAggregator", "aresModalShelf", "officeSelectorUtil", "aresConfirmDialog", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; return { templateUrl: "/app/supplychain/views/product-unity/inventory-product-unity-list-view.html", controller: "InventoryProductUnityListCtrl", link: function(n, u) { var w = function(i) { t(function() { var t = h.open({ title: i ? "编辑物品" : "新增物品", titleIconClass: i ? "iconfont icon-bianji" : "iconfont icon-addition", template: "<spu-edit-basic-view><\/spu-edit-basic-view>", controller: "SpuEditBasicCtrl", resolve: { host: function() { return { productUnityId: i, preSelectedCategory: n.selectedCategory } } }, confirmClose: !i });
                        t.result.then(function() { n.search();
                            n.getReplaceableSpuCount() }) }, 100) },
                b = function() { if (!n.canChangeCategory) { var t = u.find("#inventory-product-unity-list-update-category-btn");
                        t.tooltip("show"); return } },
                k = function() { var t = _.find(n.productUnityList, function(n) { return n.changeCategoryChecked }),
                        i = n.categoryNodeMap[t.categoryId],
                        f = r.open({ animation: !0, backdrop: "static", template: "<product-category-select-modal-view><\/product-category-select-modal-view>", controller: "ProductCategorySelectModalCtrl", windowClass: "product-category-select-modal-wrapper", backdropClass: "inventory-modal-backdrop", size: "md", resolve: { host: function() { return { categoryTreeData: n.categoryTreeData, selectedCategory: i, mode: "full" } } } });
                    f.result.then(function(t) { n.updateCategory(t).then(function() { o.success("切换分类成功");
                            u.find("#checkbox-all-products").prop("checked", !1);
                            n.search() }) }) },
                d = function() { var r = _.filter(n.productUnityList, function(n) { return n.changeCategoryChecked }),
                        e = _.map(r, function(n) { return parseInt(n.id) }),
                        s = { officeTreeData: n.officeTreeData, selectMode: "officeOnly", checkbox: !0, title: "选择机构", allowNoneSelection: !0, selectedOfficeIds: [f.officeId] },
                        i = [];
                    c.open(s).then(function(t) { l.confirm({ message: "确定修改可见机构？" }).then(function() { var r = _.map(t, function(n) { return parseInt(n.officeId) }),
                                s;
                            r.push(f.officeId);
                            _.each(n.allOfficeIds, function(n) { r.indexOf(n) === -1 && i.push(n) });
                            s = { productUnityIds: e, officeIds: i, isAvailable: !1 };
                            n.saveProductOffices(s).then(function() { o.success("分配机构成功");
                                u.find("#checkbox-all-products").prop("checked", !1);
                                n.search() }) }) });
                    t(function() { angular.element.find(".office-selector-dialog-modal-wrapper div.k-top.k-bot input[type=checkbox]")[0].checked = !0 }, 100) },
                g = function(t) { var i = h.open({ title: "库存预警设置", template: "<product-warn-rule-config-view><\/product-warn-rule-config-view>", controller: "ProductWarnRuleConfigCtrl", resolve: { host: function() { return { productUnityId: t.productUnityId, products: t.products } } } });
                    i.result.then(function() { n.search() }, 100) },
                nt = function(t) { var i = window.event ? t.keyCode : t.which;
                    i == 13 && n.search() },
                y = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } },
                tt = function() { n.initProductCodeOptions().then(function() { v();
                        a();
                        angular.element(i).on("resize", function() { v();
                            a() }) }) },
                a = function() { var f = angular.element(i).height(),
                        t = u.find(".category-menu-tree"),
                        r = f - 185 - (window.Ares3 ? 20 : 0);
                    n.showAdvancedSearchBar && (r -= 52);
                    t.height(r);
                    t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar(y) },
                it = function() { a();
                    n.categoryTreeInstance.expand("li:first, li:first li") },
                v = function() { var e = angular.element(i).height(),
                        o = u.find(".list-container"),
                        s = o.closest(".main-content-container").width() - 260,
                        f = s - (n.productCodeOptions.allowInsideCode ? 408 : 283),
                        t, r;
                    n.basicInfoTdWidth = f * .7;
                    n.specTdWidth = f * .3;
                    t = u.find(".list-table-body-container");
                    r = e - 245;
                    n.showAdvancedSearchBar && (r -= 52);
                    n.productUnityList && n.productUnityList.length !== 0 && n.page.pageCount && n.page.pageCount !== 1 || (r += 48);
                    t.height(r - (window.Ares3 ? 20 : 0));
                    t.data("mCustomScrollbarIndex") ? t.mCustomScrollbar("update") : t.mCustomScrollbar(_.extend({}, y, { callbacks: { whileScrolling: function() { t.find(".specification-dropdown-anchor").popover("hide") } } }));
                    u.find(".list-table-body").find('[data-toggle="tooltip"]').tooltip() },
                rt = function() { t(function() { var n = u.find(".list-table-body-container");
                        n.data("mCustomScrollbarIndex") && n.mCustomScrollbar("scrollTo", "top") }, 100) },
                ut = function(t) { n.enableStatus = t;
                    n.search() },
                ft = function() { n.expandedCategoryIds = n.categoryTreeInstance.getExpandedIds(); var i = e.open("<product-category-management-view><\/product-category-management-view>", "ProductCategoryManagementCtrl", { host: function() { return { selectedCategory: n.selectedCategory } } }, n);
                    i.result.then(function() { n.initProductCategoryData().then(function() { t(function() { n.categoryTreeInstance.restoreExpanded(n.expandedCategoryIds) }) }) }) },
                p = function(t) { n.selectedCategory = t;
                    n.search() },
                et = function() { p(null) },
                ot = function(t) { var i = $(t.target);
                    i.prop("checked") ? (n.canChangeCategory = !0, _.each(n.productUnityList, function(n) { n.changeCategoryChecked = !0 })) : (n.canChangeCategory = !1, _.each(n.productUnityList, function(n) { n.changeCategoryChecked = !1 }));
                    n.showChangeCategoryDisabledHint = !1 },
                st = function() { n.canChangeCategory = _.some(n.productUnityList, function(n) { return n.changeCategoryChecked });
                    n.showChangeCategoryDisabledHint = !1 },
                ht = function(t, i) { n.selectedProductUnity = t;
                    $(i.target).popover("show") },
                ct = function(n) { var u = $(n.target),
                        f = u.data("bs.popover").$tip,
                        e, r, o;
                    f.find(".arrow").remove();
                    e = 0;
                    r = parseInt(u.attr("data-specification-count"));
                    r = r > 6 ? 6 : r;
                    o = r * 28 + 32;
                    angular.element(i).height() - u.offset().top < o && (e = -20 - o);
                    f.css({ padding: 0, border: 0, marginLeft: "140px", marginTop: e + "px", background: "transparent", boxShadow: "none", minHeight: "unset" });
                    t(function() { var n = f.find(".product-specification-popover-body-wrapper");
                        n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(y) }, 500) },
                lt = function(t) { if (!t.category) return ""; if (t.categoryId === 0) return t.category; for (var r = [], i = n.categoryNodeMap[t.categoryId]; i;) r.push(i.name), i = n.categoryNodeMap[i.parentId]; return r.reverse().join("-") },
                at = function(n, t) { s.publish(s.events.ProductSelected, { productId: n, isSpu: !0 }, t.delegateTarget) },
                vt = function() { s.subscribe(n, s.events.HelpSlideHidden, function() { angular.element(i).width() < 1610 || t(function() { n.basicInfoTdWidth += 235 }) });
                    s.subscribe(n, s.events.HelpSlideShown, function() { angular.element(i).width() < 1610 || t(function() { n.basicInfoTdWidth -= 235 }) }) },
                yt = function() { n.showAdvancedSearchBar = !n.showAdvancedSearchBar;
                    a();
                    v() },
                pt = function() { n.isMatchBaseLcSPU = !n.isMatchBaseLcSPU;
                    n.search() },
                wt = function() { var t = u.find("#inventory-product-unity-list-update-category-btn");
                    t.tooltip({ template: '<div class="tooltip tooltip-danger" role="tooltip"><div class="tooltip-arrow"><\/div><div class="tooltip-inner"><\/div><\/div>' }).on("show.bs.tooltip", function(t) { n.canChangeCategory && t.preventDefault() }) },
                bt = function(t, i) { var r = angular.element(i.target);
                    r.popover("show");
                    n.currentIgnoreMatchLcPopover.spuId = t.id;
                    n.currentIgnoreMatchLcPopover.anchor = r },
                kt = function(n) { var t = $(n.target),
                        i = t.data("bs.popover").$tip;
                    i.css("minHeight", "unset") },
                dt = function() { n.currentIgnoreMatchLcPopover.anchor.popover("hide");
                    n.currentIgnoreMatchLcPopover.anchor = null;
                    n.currentIgnoreMatchLcPopover.spuId && n.ignoreProductUntiyMatch(n.currentIgnoreMatchLcPopover.spuId) };
            (function() { n.listHeight = { height: angular.element(window).height() - 245 };
                n.productUnityWith = { width: angular.element(window).width() - 970 };
                n.productHeaderWith = { width: angular.element(window).width() - 920 };
                n.productHalfWith = { width: (angular.element(window).width() - 970) / 2 };
                n.showAdvancedSearchBar = !1;
                n.openEditProductDialog = w;
                n.openRemindConfigDialog = g;
                n.onEnableChange = ut;
                n.onEnter = nt;
                n.initTableView = v;
                n.initTreeView = a;
                n.onTreeViewInit = it;
                n.scrollToTop = rt;
                n.isGroup = f.isGroup;
                n.openCategoryManagementModal = ft;
                n.onCategorySelect = p;
                n.onSelectAllCategory = et;
                n.categoryTreeInstance = null;
                n.expandedCategoryIds = [];
                n.toggleCheckAll = ot;
                n.openUpdateCategoryDialog = k;
                n.openUpdateOfficeDialog = d;
                n.checkBatch = b;
                n.canChangeCategory = !1;
                n.checkCanChangeCategory = st;
                n.showChangeCategoryDisabledHint = !1;
                n.showSpecificationPopover = ht;
                n.onShowSpecificationPopover = ct;
                n.getCategoryBreadcrumbHtml = lt;
                n.onSelectProduct = at;
                n.toggleAdvancedSearchBar = yt;
                n.toggleMatchPlatform = pt;
                n.currentIgnoreMatchLcPopover = { anchor: null, spuId: null };
                n.showIgnoreReplaceablePopover = bt;
                n.onIgnoreReplaceablePopoverShow = kt;
                n.onIgnoreSpuMatchLc = dt;
                tt();
                wt();
                vt();
                n.selectedOfficeIds = [];
                n.onOfficeSelectorHidden = function(t) { t !== null && (n.selectedOfficeIds = [t], n.search()) } })() } } }]);
supplychainModule.directive("productRemindConfigView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "inventoryUtil", "enums", "aresConfirmDialog", function(n, t, i, r, u, f, e, o) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/product-remind-config-view.html", link: function(n, i) { var s = function() { n.productWarnRule && (n.productWarnRule.isEnabled = !n.productWarnRule.isEnabled) },
                r = function(n, t) { t === 0 ? (n.ruleData = f.formatNumber(n.ruleData, !0), n.ruleData <= 0 && (n.ruleData = 0)) : (n.lowLimit = f.formatNumber(n.lowLimit, !0), n.lowLimit <= 0 && (n.lowLimit = 0)) },
                h = function(n, t) { t === 0 ? (n.ruleData = parseInt(n.ruleData), n.ruleData -= 1) : (n.lowLimit = parseInt(n.lowLimit), n.lowLimit -= 1);
                    r(n, t);
                    event.preventDefault() },
                c = function(n, t) { t === 0 ? (n.ruleData = parseInt(n.ruleData), n.ruleData += 1) : (n.lowLimit = parseInt(n.lowLimit), n.lowLimit += 1);
                    r(n, t);
                    event.preventDefault() },
                l = function() { n.productWarnRule.warehouseProductOptions || (n.productWarnRule.warehouseProductOptions = []); var t = { warehouseId: 0, lowLimit: n.inventoryCountLowLimit };
                    n.productWarnRule.warehouseProductOptions.push(t) },
                a = function(t) { n.productWarnRule && n.productWarnRule.warehouseProductOptions && n.productWarnRule.warehouseProductOptions.splice(t, 1) },
                v = function(t) { var i = n.productWarnRule.warehouseProductOptions,
                        r = _.pluck(i, "warehouseId"),
                        f = _.filter(r, function(n) { return t.warehouseId == n });
                    f.length > 1 && t.warehouseId != 0 && (t.warehouseId = "", u.error("预警仓库不能重复选择！")) },
                y = function(n) { var t = this.dataItem(n.item.index());
                    t.grade === e.WarehouseGrade.Consignee.value && (n.preventDefault(), o.warn({ message: "寄售仓库不能设置库存预警" })) };
            (function() { n.mainHeight = { height: $(window).height() - 180 };
                n.setEnable = s;
                n.reduceNum = h;
                n.plusNum = c;
                n.onCountChanged = r;
                n.onWarehouseSelected = y;
                n.addWarehouseProductOption = l;
                n.deleteWarehouseProductOption = a;
                n.onHandleWarehousesSelect = v;
                t(function() { Ares.centerModal(i.closest(".modal-dialog")) }, 100) })() } } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n() { this.templateUrl = "/app/supplychain/views/product-unity/dialogs/product-warn-rule-config/product-warn-rule-config-view.html";
            this.replace = !0;
            this.restrict = "E";
            this.link = function() {} } return n.$inject = [], n }();
    supplychainModule.directive("productWarnRuleConfigView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { "use strict"; var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l) { this.$scope = n;
            this.$q = t;
            this.officeOptionSvc = i;
            this.inventoryUtil = r;
            this.productWarnRuleSvc = u;
            this.host = f;
            this.$log = e;
            this.aresNotification = o;
            this.$modalInstance = s;
            this.enums = h;
            this.$timeout = c;
            this.aresConfirmDialog = l;
            n.products = this.host.products;
            n.productMap = {};
            _.each(n.products, function(t) { t.name = t.specAndUnit;
                n.productMap[t.id] = t });
            this._initData();
            n.rulesGroup = { global: { productIds: [], lowLimit: 0 }, individual: [], warehouse: [] } } return n.prototype.save = function() { var n = this;
            this._validateProductRemindConfig().then(function(t) { n.productWarnRuleSvc.save(t).then(function() { n.aresNotification.success("保存成功");
                    n.$modalInstance.close(!0) }) }) }, n.prototype.updateProductSources = function() { var n = this;
            this.$timeout(function() { var t = n.$scope,
                    i = [].concat(t.rulesGroup.global.productIds),
                    r, u;
                _.each(t.rulesGroup.individual, function(n) { i = i.concat(n.productIds) });
                _.each(t.rulesGroup.warehouse, function(n) { i = i.concat(n.productIds) });
                r = _.filter(t.products, function(n) { return i.indexOf(n.id) < 0 });
                u = _.filter(t.products, function(n) { return t.rulesGroup.global.productIds.indexOf(n.id) > -1 }).concat(r);
                t.rulesGroup.global.productSource = _.sortBy(u, "productId");
                _.each(t.rulesGroup.individual, function(n) { var i = _.filter(t.products, function(t) { return n.productIds.indexOf(t.id) > -1 }).concat(r);
                    n.productSource = _.sortBy(i, "productId") });
                _.each(t.rulesGroup.warehouse, function(n) { var i = _.filter(t.products, function(t) { return n.productIds.indexOf(t.id) > -1 }).concat(r);
                    n.productSource = _.sortBy(i, "productId") }) }) }, n.prototype.addGroup = function(n) { this.$scope.rulesGroup[n].push({ productIds: [], lowLimit: 0, warehouseId: 0 });
            this.updateProductSources() }, n.prototype.deleteGroup = function(n, t) { this.$scope.rulesGroup[n].splice(t, 1);
            this.updateProductSources() }, n.prototype._flattenRules = function() { var i = this,
                n = this.$scope,
                t = []; return _.each(n.rulesGroup.global.productIds, function(r) { var u = n.productMap[r],
                    f = { productId: r, productUnityId: u.productUnityId, lowLimit: n.globalLowLimit, ruleType: 0, warnMethod: i.enums.ProductWarnMethod.ByOffice, isEnabled: n.isEnabled };
                t.push(f) }), _.each(n.rulesGroup.individual, function(r) { _.each(r.productIds, function(u) { var f = n.productMap[u],
                        e = { productId: u, productUnityId: f.productUnityId, lowLimit: r.lowLimit, ruleType: 0, warnMethod: i.enums.ProductWarnMethod.BySingle, isEnabled: n.isEnabled };
                    t.push(e) }) }), _.each(n.rulesGroup.warehouse, function(r) { _.each(r.productIds, function(u) { var f = n.productMap[u],
                        e = { productId: u, productUnityId: f.productUnityId, lowLimit: r.lowLimit, ruleType: 0, warnMethod: i.enums.ProductWarnMethod.ByWarehouse, isEnabled: n.isEnabled, warehouseId: r.warehouseId };
                    t.push(e) }) }), t }, n.prototype._validateProductRemindConfig = function() { var r = this,
                i = this.$q.defer(),
                n, t; return (_.any(this.$scope.rulesGroup.individual, function(n) { return n.productIds.length === 0 }) || _.any(this.$scope.rulesGroup.warehouse, function(n) { return n.productIds.length === 0 })) && (n = "请选择规格"), t = this._flattenRules(), t.length === 0 && (n = "请至少配置一条规则。<br>如需禁用所有规则，可关闭启用开关。"), _.each(t, function(t) { if (!t.lowLimit || t.lowLimit === "0") { n = "预警值应大于0"; return } t.warnMethod !== r.enums.ProductWarnMethod.ByWarehouse || t.warehouseId && t.warehouseId !== "0" || (n = "请选择仓库") }), n ? (this.aresConfirmDialog.error({ message: n }), i.reject()) : i.resolve(t), i.promise }, n.prototype._initData = function() { var n = this,
                t = this.$scope;
            this._initOfficeOption().then(function() { n.inventoryUtil.initWarehouses().then(function(i) { i = i || [];
                    i = _.filter(i, function(t) { return t.grade !== n.enums.WarehouseGrade.Consignee.value });
                    i.unshift({ id: 0, name: "请选择仓库" });
                    t.warehouses = i;
                    n._initProductWarnRule() }) }) }, n.prototype._initProductWarnRule = function() { var n = this,
                t = this.$q.defer(),
                i = _.pluck(this.$scope.products, "id"); return this.productWarnRuleSvc.get(i).success(function(i) { i = i || [];
                n.$scope.isEnabled = i.length > 0 && _.any(i, function(n) { return n.isEnabled });
                n._groupRules(i);
                n.updateProductSources();
                t.resolve(!0) }).error(function(i) { n.$log.log(i.message);
                t.reject() }), t.promise }, n.prototype._groupRules = function(n) { var i = this,
                t = this.$scope,
                r = _.filter(n, function(n) { return n.warnMethod === i.enums.ProductWarnMethod.ByOffice }),
                u, f, e, o;
            t.rulesGroup.global.lowLimit = t.globalLowLimit;
            r.length > 0 && (t.rulesGroup.global.productIds = _.pluck(r, "productId"));
            u = _.filter(n, function(n) { return n.warnMethod === i.enums.ProductWarnMethod.BySingle });
            f = _.groupBy(u, "lowLimit");
            _.each(f, function(n, i) { t.rulesGroup.individual.push({ lowLimit: parseInt(i), productIds: _.pluck(n, "productId") }) });
            e = _.filter(n, function(n) { return n.warnMethod === i.enums.ProductWarnMethod.ByWarehouse });
            o = _.groupBy(e, function(n) { return n.warehouseId + "$$$" + n.lowLimit });
            _.each(o, function(n, i) { var r = parseInt(i.split("$$$")[0]),
                    u = parseInt(i.split("$$$")[1]),
                    f = _.find(t.warehouses, function(n) { return n.id === r });
                t.rulesGroup.warehouse.push({ lowLimit: u, productIds: _.pluck(n, "productId"), warehouseId: f.id }) }) }, n.prototype._initOfficeOption = function() { var t = this,
                n = this.$scope,
                i = this.$q.defer(); return this.officeOptionSvc.getOfficeOption(this.officeOptionSvc.optionKeys.IsInventoryCountWarnEnabled).then(function(r) { n.isInventoryCountWarnEnabled = r;
                t.officeOptionSvc.getOfficeOption(t.officeOptionSvc.optionKeys.InventoryCountLowLimit).then(function(t) { n.globalLowLimit = parseInt(t);
                    n.globalLowLimit = n.isInventoryCountWarnEnabled ? t : 5;
                    n.globalLowLimitStr = n.isInventoryCountWarnEnabled ? t : "未配置";
                    i.resolve(!0) }) }), i.promise }, n.$inject = ["$scope", "$q", "officeOptionSvc", "inventoryUtil", "productWarnRuleSvc", "host", "$log", "aresNotification", "$modalInstance", "enums", "$timeout", "aresConfirmDialog"], n }();
    supplychainModule.controller("ProductWarnRuleConfigCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("skuPlatformReplaceDialogView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", function(n, t) { return { replace: !0, restrict: "EA", templateUrl: "/app/supplychain/views/product-unity/dialogs/sku-platform-replace-dialog/sku-platform-replace-dialog-view.html", link: function(n, i) { "use strict"; var r = i.find(".sku-platform-replace-table-body"),
                u = function() { r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) };
            (function() { t(function() { Ares.centerModal(i.closest(".modal-dialog"));
                    u() }, 100) })() } } }]);
supplychainModule.controller("SkuPlatformReplaceDialogCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "host", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var s = function() { f.dismiss() },
        h = function() { t.platformSkus = _.map(e.platformSkus, function(n) { return n.toSpecAndUnit = "不替换", n }); var n = e.currentSkus || [];
            n.unshift({ specAndUnit: "不替换" });
            t.currentSkus = n },
        c = function() { var i = [],
                n = [],
                r = []; if (_.each(t.platformSkus, function(t) { t.toSpecAndUnit === "不替换" ? i.push(t) : (n.push(t), r.push(t.toSpecAndUnit)) }), _.uniq(r).length !== n.length) { o.error("不能重复选择相同的替换规格"); return } f.close({ addSkus: i, replaceSkus: n }) };
    (function() { t.closeThePopup = s;
        t.onSave = c;
        h() })() }]);
supplychainModule.controller("SkuSelectCtrl", ["$log", "$scope", "$timeout", "$q", "productSvc", "$modalInstance", "host", "loginContext", "inventoryProductSvc", "inventorySvc", "dataDicSvc", "aresNotification", "officeSelectorUtil", "officeSvc", "procurementSvc", "reportUtil", "inventoryUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) { "use strict"; var g = function() { if (t.nextPageIndex === -1) return r.when([]);
            t.nextPageIndex === 1 && (t.productUnityList = [], t.payOrderList = []); switch (t.type) {
                case "productListWithoutCount":
                    return t.isShowSearch = !0, t.isShowFreeFieldSearch = !0, k();
                case "inOrder":
                    return t.isShowSearch = !0, k();
                case "takeOrderList":
                    return t.isShowSearch = !0, t.isInventoryTake = !0, k();
                case "historyProcurement":
                    return t.isShowCategory = !1, t.isShowSearch = !0, t.canSelectDisabled = !1, nt();
                case "historyTakeOrder":
                    return t.withCount = !0, t.isShowCategory = !1, t.isShowSearch = !0, t.isInventoryTake = !0, tt();
                case "outOrder":
                    return t.isShowSearch = !0, t.withCount = !0, k();
                case "checkOrder":
                    return t.isShowSearch = !0, t.withCount = !0, t.isShowCheckbox = !0, t.includeZeroCount = !0, k();
                case "quotation":
                    return t.isShowCategory = !0, t.isShowSearch = !0, t.isShowCheckbox = !0, t.canSelectDisabled = !0, k();
                case "singleSpu":
                    return t.isShowCategory = !1, t.isShowSearch = !1, t.isShowCheckbox = !1, t.canSelectDisabled = !0, k() } },
        d = function() { if (t.nextPageIndex === -1) return !1; var n; return t.withCount ? (n = { pageIndex: t.isShowCheckbox && t.page ? t.page.pageIndex : t.nextPageIndex, pageSize: 20, searchText: t.searchName.text, categoriesIds: t.selCategoriesIds }, t.warehouseId && (n.warehouseId = t.warehouseId), t.isInventoryTake && (n.isInventoryTake = t.isInventoryTake), t.includeZeroCount && (n.includeZeroCount = t.includeZeroCount)) : (n = { isWithProducts: !0, isEnabled: !0, pageIndex: t.isShowCheckbox && t.page ? t.page.pageIndex : t.nextPageIndex, pageSize: 20, searchText: t.searchName.text, categoriesIds: t.selCategoriesIds, freeField1: t.searchFreeField.freeField1, freeField2: t.searchFreeField.freeField2, freeField3: t.searchFreeField.freeField3, dealerId: t.dealerId, isWithProductSumCount: !0, id: t.singleSpuId || null }, t.isCheckInventoryLog && (n.isCheckInventoryLog = !0), t.isInventoryTake && (n.isInventoryTake = t.isInventoryTake)), n },
        k = function() { var n = r.defer(),
                i = d(),
                f; return i ? (f = t.withCount ? s.searchLiteInventoryProductUnityGroup : u.searchProductUnityGroup, f(i).success(function(i) { t.isShowCheckbox ? (t.nextPageIndex = i.pageIndex + 1, t.page = { pageIndex: i.pageIndex, totalCount: i.totalCount, pageSize: 20, pageCount: i.pageCount }) : i.pageIndex < i.pageCount ? t.nextPageIndex++ : t.nextPageIndex = -1;
                i.items && (_.each(i.items, function(n) { t.withCount && t.type !== "checkOrder" && (n.products = _.filter(n.products, function(n) { return n.inventoryCount > 0 }));
                    _.each(n.products, function(i) { i.productId = i.id || i.productId;
                        i.name = i.name || n.name;
                        i.producer = i.producer || n.producer;
                        angular.isUndefined(i.isEnabled) && (i.isEnabled = !0);
                        t.withCount ? i.sumCount = i.sumCount || i.inventoryCount : i.inventoryCount = i.sumCount }) }), t.withCount && (i.items = _.filter(i.items, function(n) { return n.products.length > 0 })), t.productUnityList = t.isShowCheckbox ? [].concat(i.items) : t.productUnityList.concat(i.items), b());
                n.resolve(!0) })) : n.resolve(!0), n.promise },
        nt = function() { var i = r.defer(),
                n = d(); return n ? t.isProcurementItemSearch ? y.searchHistoryProcurementProduct(n).success(function(n) { n.pageIndex < n.pageCount ? t.nextPageIndex++ : t.nextPageIndex = -1;
                n.items && (_.each(n.items, function(n) { _.each(n.products, function(t) { t.isDisabled = !n.isEnabled;
                        t.name = n.name;
                        t.isEnabled = !0;
                        t.producer = n.producer }) }), t.productUnityList = t.productUnityList.concat(n.items), b());
                i.resolve(!0) }) : (t.payOrderCriteria && (n.officeIds = t.payOrderCriteria.officeIds && t.isGroup ? t.payOrderCriteria.officeIds : [o.officeId], n.supplierId = t.payOrderCriteria.dealerId, n.orderDate_SearchBegin = t.payOrderCriteria.startDate, n.orderDate_SearchEnd = t.payOrderCriteria.endDate), y.searchHistoryProcurementPayOrder(n).success(function(n) { n.pageIndex < n.pageCount ? t.nextPageIndex++ : t.nextPageIndex = -1;
                t.payOrderList = t.payOrderList.concat(n.items);
                b();
                i.resolve(!0) })) : i.resolve(!0), i.promise },
        tt = function() { var n = r.defer(),
                i = d(); return i ? h.getTakeOrderHistoryProductUnity(i).success(function(i) { i.pageIndex < i.pageCount ? t.nextPageIndex++ : t.nextPageIndex = -1;
                i.items && (_.each(i.items, function(n) { _.each(n.products, function(i) { i.name = n.name;
                        i.producer = n.producer;
                        i.isEnabled = !0;
                        i.sumCount = i.inventoryCount;
                        i.isDisabled = !t.isInventoryOverflowTakeEnabled && i.inventoryCount == 0 }) }), t.productUnityList = t.productUnityList.concat(i.items), b());
                n.resolve(!0) }) : n.resolve(!0), n.promise },
        b = function() { _.each(t.productUnityList, function(n) { n && _.each(n.products, function(n) { n.isExist = t.addedSkuList.indexOf(n.productId) > -1 }) }) },
        it = function() { f.on("SKU_EXIST_LIST", function(n) { if (n && n.data) { var i = n.data.productIds;
                    i && (t.addedSkuList = _.map(i, function(n) { return parseInt(n) }), b()) } });
            f.on("SKU_SELECT_ADDED", function(n) { if (n && n.data) { var i = n.data.productId;
                    i && (t.addedSkuList.push(i), b()) } });
            f.on("SKU_SELECT_REMOVED", function(n) { if (n && n.data) { var i = n.data.productId;
                    i && (t.addedSkuList = _.without(t.addedSkuList, i), b()) } });
            f.on("SUPPLIER_SELECTED", function(n) { if (n && n.data) { var i = n.data; if (t.dealerId = i.isLinkedCare ? i.dealerId : null, t.onSearchProductUnity) t.onSearchProductUnity(!0) } });
            f.on("WITH_COUNT_CHANGE", function(n) { if (n && n.data && t.type === "takeOrderList" && (t.withCount = n.data.withCount, t.onSearchProductUnity)) t.onSearchProductUnity(!0) });
            f.on("WAREHOUSE_ID_CHANGE", function(n) { if (n && n.data && (t.type === "outOrder" || t.type === "checkOrder") && (t.warehouseId = n.data.warehouseId, t.onSearchProductUnity)) t.onSearchProductUnity(!0) });
            f.on("SWITCH_SKU_SELECT_TYPE", function(n) { if (n && n.data && (t.type = n.data.type, t.singleSpuId = t.type === "singleSpu" ? n.data.spuId : null, t.onSearchProductUnity)) t.onSearchProductUnity(!0) }) },
        rt = function(n, t) { if (!n.isExist && !n.isDisabled || t) { if (t) return u.getProductDealersByProductIds({ dealerId: t, productIds: [n.productId] }).success(function(i) { n.dealers = i;
                    _.each(n.dealers, function(n) { n.dealerId === t && (n.isPreferred = !0) });
                    f.broadcast("SKU_SELECT_ADD", { sku: n }) });
                f.broadcast("SKU_SELECT_ADD", { sku: n }) } },
        ut = function(n) { if (n && n.items) { var t = _.pluck(n.items, "productId"); return u.getProductDealersByProductIds({ order: n.supplierId, productIds: t }).success(function(t) { _.each(n.items, function(i) { var r = _.filter(t, function(n) { return n.productId === i.productId });
                        _.each(r, function(t) { t.isPreferred = t.dealerId === n.supplierId ? !0 : !1 });
                        i.dealers = r;
                        f.broadcast("SKU_SELECT_ADD", { sku: i }) }) }) } },
        ft = function() { c.officeSettingDic.load().then(function(n) { t.isInventoryOverflowTakeEnabled = n.isInventoryOverflowTakeEnabled;
                c.systemItemDic.loadActive().then(function(n) { if (n) { var i = _.filter(n, { itemType: "物品自由项" });
                        i && (t.freeField1 = _.find(i, { itemName: "物品自由项1" }), t.freeField2 = _.find(i, { itemName: "物品自由项2" }), t.freeField3 = _.find(i, { itemName: "物品自由项3" }));
                        t.freeField1DataSource = _.filter(n, { itemType: "物品自由项1选项" });
                        t.freeField1DataSource.unshift({ itemName: "" });
                        t.freeField2DataSource = _.filter(n, { itemType: "物品自由项2选项" });
                        t.freeField2DataSource.unshift({ itemName: "" });
                        t.freeField3DataSource = _.filter(n, { itemType: "物品自由项3选项" });
                        t.freeField3DataSource.unshift({ itemName: "" }) } }) }) },
        et = function() { _.each(t.productUnityList, function(n) { n.checked = t.uiState.checkAll }) },
        ot = function(n) { t.uiState.checkAll = n.checked ? _.every(t.productUnityList, function(n) { return n.checked }) : !1 },
        st = function() { var n = _.filter(t.productUnityList, function(n) { return n.checked }); if (n.length === 0) { l.error("请选择需要添加的物品"); return } _.each(n, function(n) { _.each(n.products, function(n) { t.addedSkuList.indexOf(n.id) < -1 && t.addedSkuList.push(n.id) }) });
            t.$modalInstance.broadcast("SPU_BATCH_ADD", { spus: n });
            b() },
        ht = function() { t.$modalInstance.broadcast("SPU_BATCH_ADD", { spus: t.productUnityList });
            b() },
        ct = function() { t.selDealerId = 0; var n = r.defer(); return c.dealerDic.loadActive().then(function(i) { t.dealers = i;
                t.dealers.splice(0, 0, { id: 0, name: "所属供应商" });
                n.resolve(!0) }), n.promise },
        lt = function() { v.getSelfAndChildOfficesByGroupId(o.officeId, !0).success(function(n) { t.officeTreeData = a.setId(n); var i = _.values(a.flattenToMap(n));
                t.payOrderCriteria.officeIds = _.pluck(i, "officeId") }) },
        at = function() { t.isShowCheckbox && (t.uiState.checkAll = !1);
            t.$apply() };
    (function() { t.type = e.type;
        t.isCheckInventoryLog = e.isCheckInventoryLog;
        t.warehouseId = e.warehouseId;
        t.withCount = e.withCount;
        t.productUnityList = [];
        t.nextPageIndex = 1;
        t.addedSkuList = [];
        t.isShowSearch = !1;
        t.isShowCategory = !0;
        t.searchName = {};
        t.searchFreeField = {};
        t.page = { pageIndex: 1, totalCount: 0, pageSize: 20, pageCount: 1 };
        t.uiState = { checkAll: !1 };
        t.searchProductUnityList = g;
        t.onSkuAddBtnClick = rt;
        t.onOrderAddBtnClick = ut;
        t.toggleCheckAll = et;
        t.checkCheckAll = ot;
        t.batchSelect = st;
        t.batchSelectSingleSpu = ht;
        t.isGroup = o.isGroup;
        t.resetUIState = at;
        ft();
        it();
        i(function() { t.type && t.type === "historyProcurement" && (t.isHistoryProcurement = !0, t.isProcurementItemSearch = !0, w.getGroupProcurementConfigs().then(function(n) { if (t.groupSalesEnabled = n.groupSalesEnabled, !t.groupSalesEnabled) { var i = p.getDefaultTimeSpan();
                    t.searchTimeRange = { startDate: i.startTime, endDate: i.endTime };
                    t.payOrderCriteria = { dealerId: 0, startDate: i.startTime, endDate: i.endTime, officeIds: [], showDetail: !0 };
                    ct();
                    t.isGroup && lt() } })) }, 0, !1) })() }]);
supplychainModule.directive("skuSelectView", ["$log", "$q", "$timeout", "$window", "inventoryUtil", "aresTreeViewUtil", "eventAggregator", function(n, t, i, r, u, f, e) { "use strict"; return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/sku-select-dialog/sku-select-view.html", link: function(n, t) { var c = function() { u.getProductCategories().then(function(t) { n.selCategoryId = 0;
                        n.selCategory = { name: "全部分类", id: 0 };
                        n.categoriesTree = f.unflatten(t, "showOrder");
                        n.categoriesTree.splice(0, 0, n.selCategory) }) },
                s = function(r) { var u = t.find(".sku-result-list-container"),
                        e = t.parent().height(),
                        f = e - 80;
                    n.isShowCheckbox && (f -= 32);
                    n.isShowSearch || (f += 50);
                    n.isHistoryProcurement && !n.isProcurementItemSearch && (f -= 75);
                    u.height(f);
                    u.data("mCustomScrollbarIndex") ? (u.mCustomScrollbar("update"), i(function() { r && u.mCustomScrollbar("scrollTo", "top") }, 0, !1)) : u.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0 }, mouseWheel: { preventDefault: !0 }, callbacks: { whileScrolling: function(t) { n.isShowCheckbox || n.type === "singleSpu" || t.topPct >= 90 && n.nextPageIndex !== -1 && o() } } }) },
                l = function(t) { n.selCategory = t;
                    n.categoryId = t.id;
                    n.selCategoriesIds = u.getAllSubCategoriesIds(t);
                    o(!0) },
                a = function(n) { var t = window.event ? n.keyCode : n.which;
                    t === 13 && o(!0) },
                o = function(r) { r && (n.nextPageIndex = 1); var u = t.find(".sku-result-list-container");
                    n.isSearching || (n.isSearching = !0, n.searchProductUnityList().then(function() { n.isSearching = !1;
                        i(function() { s(r || n.isShowCheckbox);
                            h();
                            d() }, 0, !1) })) },
                v = function(t) { n.isProcurementItemSearch = t;
                    n.searchTextPlaceholder = n.isHistoryProcurement && !n.isProcurementItemSearch ? "采购单号/商城订单号" : "物品名称/品牌/规格/内部编码";
                    o(!0) },
                y = function(t) { n.payOrderCriteria.startDate = t.startDate;
                    n.payOrderCriteria.endDate = t.endDate;
                    o(!0) },
                p = function(t) { n.payOrderCriteria.officeIds = _.pluck(t, "officeId");
                    o(!0) },
                w = function(n, t) { var i = n.productId || item.id;
                    e.publish(e.events.ProductSelected, i, t.delegateTarget) },
                b = function() { i(function() { s(!0);
                        h() }, 0, !1) },
                k = function() { n.categorySelectHeight = angular.element(r).height() - 250;
                    c();
                    o(!0) },
                h = function() { t.find('[data-toggle="tooltip"]').tooltip({ container: ".form-list-body" }) },
                d = function() { n.resetUIState() };
            (function() { n.onEnter = a;
                n.onSearchProductUnity = o;
                n.onProductCategoryChange = l;
                n.onProcurementSearchChange = v;
                n.onSearchTimeRangeChanged = y;
                n.onOfficeSelected = p;
                n.onSelectProduct = w;
                n.showPayOrderDetail = b;
                n.searchTextPlaceholder = "物品名称/品牌/规格/内部编码";
                k() })() } } }]);
var inventory;
(function() { "use strict"; var n = function() {
        function n(n) { var t = this;
            this.$timeout = n;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/product-unity/dialogs/spu-edit-batch-exp-modal/spu-edit-batch-exp-modal-view.html";
            this.link = function(n, i) {
                function f(n) { var t = i.find(n);
                    t.tooltip("show");
                    u.$timeout(function() { t.tooltip("hide") }, 1e3) }

                function e(n) { u.$timeout(function() { i.find('[data-toggle="tooltip"]').tooltip();
                        r.height(i.parent().height() - 130);
                        r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }); switch (n) {
                            case "batchNumber":
                                f(".icon-gantanhao.batch-tooltip"); break;
                            case "expiredDate":
                                f(".icon-gantanhao.exp-tooltip") } }, 0, !1) } var u = t,
                    r = i.find(".table-main-content");
                (function() { n.refreshView = e;
                    n.groupBatches();
                    n.refreshView() })() } } return n.$inject = ["$timeout"], n }();
    supplychainModule.directive("spuEditBatchExpModalView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { var n = function() {
        function n(n, t, i, r, u, f) { this.$scope = n;
            this.host = t;
            this.inventorySvc = i;
            this.aresConfirmDialog = r;
            this.aresNotification = u;
            this.$modalInstance = f;
            this.batches = [];
            this.batches = t.batches;
            this.originalIsBatchNoEnabled = t.isBatchNoEnabled;
            this.originalIsExpiredDateEnabled = t.isExpiredDateEnabled;
            this.originalValuationType = t.valuationType;
            this.productUnityId = t.productUnityId;
            n.uiState = { canEditBatchNo: !1, canEditExpiredDate: !1, isBatchNoEnabled: t.isBatchNoEnabled, isExpiredDateEnabled: t.isExpiredDateEnabled, valuationType: t.valuationType } } return n.prototype.groupBatches = function() { var t = _.groupBy(this.batches, function(n) { return n.expiredDate && (n.expiredDate = moment(n.expiredDate).format("YYYY-MM-DD")), n.warehouseId + "&&&" + n.productId }),
                n = _.map(_.values(t), function(n) { var t = n[0],
                        i = _.reduce(n, function(n, t) { return n + t.count }, 0); return { name: t.productName, specification: t.specification, unit: t.unit, count: i, warehouseId: t.warehouseId, warehouseName: t.warehouseName, batches: n } });
            n = _.sortBy(n, "warehouseId");
            this.$scope.items = n }, n.prototype.addBatch = function(n) { var t = _.extend({}, n.batches[0], { batchNumber: "", expiredDate: "", count: 0 });
            n.batches.push(t);
            this.$scope.refreshView() }, n.prototype.removeBatch = function(n, t) { n.batches.splice(t, 1);
            this.$scope.refreshView() }, n.prototype.switchState = function(n) {
            (n === "batchNumber" || n === "expiredDate") && this.$scope.refreshView(n);
            this.$scope.uiState.canEditBatchNo = this.$scope.uiState.isBatchNoEnabled && !this.originalIsBatchNoEnabled;
            this.$scope.uiState.canEditExpiredDate = this.$scope.uiState.isExpiredDateEnabled && !this.originalIsExpiredDateEnabled }, n.prototype.validate = function() { var n; if (n = _.find(this.$scope.items, function(n) { var t = _.reduce(n.batches, function(n, t) { return n + t.count }, 0); return t !== n.count }), n) return "仓库【" + n.warehouseName + "】各批次数量总计应与库存数量相等"; if (n = _.find(this.$scope.items, function(n) { return _.any(n.batches, function(n) { return !n.count }) }), n) return "仓库【" + n.warehouseName + "】有批次数量为0"; if (n = _.find(this.$scope.items, function(n) { return _.any(n.batches, function(n) { if (!n.expiredDate) return !1; var t = n.expiredDate.match(/^\d{4}-\d{2}-\d{2}$/); return !t }) }), n) return "仓库【" + n.warehouseName + "】有批次有效期格式有误"; if (this.$scope.uiState.isBatchNoEnabled && this.$scope.uiState.isExpiredDateEnabled) { if (n = _.find(this.$scope.items, function(n) { return _.any(n.batches, function(n) { return !n.batchNumber && !n.expiredDate }) }), n) return "仓库【" + n.warehouseName + "】有批次未填写批号或有效期"; if (n = _.find(this.$scope.items, function(n) { var t = _.map(n.batches, function(n) { return (n.batchNumber || "") + "&&&" + (n.expiredDate || "") }); return _.unique(t).length < t.length }), n) return "仓库【" + n.warehouseName + "】有重复的批号和有效期" } else if (this.$scope.uiState.isBatchNoEnabled && !this.$scope.uiState.isExpiredDateEnabled) { if (n = _.find(this.$scope.items, function(n) { return _.any(n.batches, function(n) { return !n.batchNumber }) }), n) return "仓库【" + n.warehouseName + "】有批次未填写批号"; if (n = _.find(this.$scope.items, function(n) { var t = _.pluck(n.batches, "batchNumber"); return _.unique(t).length < t.length }), n) return "仓库【" + n.warehouseName + "】有重复的批号" } else if (!this.$scope.uiState.isBatchNoEnabled && this.$scope.uiState.isExpiredDateEnabled) { if (n = _.find(this.$scope.items, function(n) { return _.any(n.batches, function(n) { return !n.expiredDate }) }), n) return "仓库【" + n.warehouseName + "】有批次未填写有效期"; if (n = _.find(this.$scope.items, function(n) { var t = _.pluck(n.batches, "expiredDate"); return _.unique(t).length < t.length }), n) return "仓库【" + n.warehouseName + "】有重复的有效期" } return !1 }, n.prototype.save = function() { var n = this,
                i = this.validate(),
                t; if (i) { this.aresNotification.error(i); return } if (this.$scope.uiState.isBatchNoEnabled || this.$scope.uiState.isExpiredDateEnabled || (this.$scope.uiState.valuationType = 0), this.originalIsBatchNoEnabled === this.$scope.uiState.isBatchNoEnabled && this.originalIsExpiredDateEnabled === this.$scope.uiState.isExpiredDateEnabled && this.originalValuationType === this.$scope.uiState.valuationType) { this.$modalInstance.close(); return } t = "当前物品批次设置发生变更，库存将通过虚拟出入库重新进行分配，确定执行该操作吗？";
            (this.originalIsBatchNoEnabled && !this.$scope.uiState.isBatchNoEnabled || this.originalIsExpiredDateEnabled && !this.$scope.uiState.isExpiredDateEnabled) && (t = "当前物品批次设置发生变更，会丢失之前录入的批次信息，库存将通过虚拟出入库重新进行分配，确定执行该操作吗？");
            this.aresConfirmDialog.warn({ message: t, showCancelBtn: !0 }).then(function() { var t = { isBatchNoEnabled: n.$scope.uiState.isBatchNoEnabled, isExpiredDateEnabled: n.$scope.uiState.isExpiredDateEnabled, valuationType: n.$scope.uiState.valuationType, productBatchs: [] };
                n.$scope.items.forEach(function(i) { i.batches.forEach(function(i) { t.productBatchs.push({ productId: i.productId, productUnityId: n.productUnityId, warehouseId: i.warehouseId, batchNumber: t.isBatchNoEnabled ? i.batchNumber : "", expiredDate: t.isExpiredDateEnabled ? i.expiredDate : "", count: i.count }) }) });
                n.inventorySvc.switchInventoryProductBatch(t).success(function() { n.$modalInstance.close({ isBatchNoEnabled: t.isBatchNoEnabled, isExpiredDateEnabled: t.isExpiredDateEnabled, valuationType: t.valuationType }) }) }) }, n.$inject = ["$scope", "host", "inventorySvc", "aresConfirmDialog", "aresNotification", "$modalInstance"], n }();
    supplychainModule.controller("SpuEditBatchExpModalCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
supplychainModule.directive("spuEditBasicView", ["$log", "$q", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", "productUtil", "aresConfirmDialog", "inventoryUtil", function(n, t, i, r, u, f, e, o, s, h, c, l) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog/spu-edit-basic-view.html", link: function(n, f) { var g = function(t) { n.selectTab = t;
                    t === "unPacking" && n.initPackageTabTooltip() },
                nt = function() { var t, i;
                    n.productUnity && (t = function() { n.productUnity.isEnabled = !n.productUnity.isEnabled;
                        n.productUnity.products && n.productUnity.products.length > 0 && n.productUnity.products.forEach(function(t) { t.isEnabled = n.productUnity.isEnabled }) }, n.productUnity.isEnabled && n.productUnity.products && n.productUnity.products.length > 0 ? (i = _.filter(_.pluck(n.productUnity.products, "id"), function(n) { return n > 0 }), i.length > 0 ? l.checkProductInventoryCount(i).then(function(n) { n.data ? c.confirm({ message: "该物品/规格仍然有库存，系统将不允许该物品进行采购和入库，但仍然允许执行出库操作。确定禁用该物品/规格吗？" }).then(function() { t() }, function() {}) : t() }) : t()) : t()) },
                tt = function(n) { i(function() { n.specAndUnit = n.specification + "(" + n.unit + ")" }) },
                it = function(t, i) { var r = u.open({ animation: !0, backdrop: "static", template: "<sku-edit-view><\/sku-edit-view>", controller: "skuEditCtrl", windowClass: "sku-edit-view-modal-wrapper", resolve: { host: function() { return { sku: t, skus: angular.copy(n.productUnity.products) } } } });
                    r.result.then(function(t) { angular.isDefined(i) ? n.productUnity.products[i] = t : n.productUnity.products.push(t);
                        n.sortProducts();
                        v() }) },
                rt = function(t) { n.productUnity.products.splice(t, 1);
                    v() },
                ut = function(t) { var i = t ? t.id : 0;
                    n.productUnity.pictureId = i },
                a, b = function(r) { var u = t.defer(); if (!n.$modalInstance.destroyed) return a && !a.destroyed ? (a.switchTab(r), u.resolve(!0)) : (a = n.$shelfInstance.open({ tabs: [{ title: "商城匹配物品", titleIconClass: "iconfont icon-copy_", template: "<spu-platform-match-dialog-view><\/spu-platform-match-dialog-view>", controller: "SpuPlatformMatchDialogCtrl", needActive: !1, setDefault: r === 0, resolve: { host: function() { return { action: n.isEdit ? "replace" : "import" } } } }, { title: "全部商城物品", titleIconClass: "iconfont icon-daoru1", template: "<spu-platform-import-dialog-view><\/spu-platform-import-dialog-view>", controller: "SpuPlatformImportDialogCtrl", needActive: !0, setDefault: r === 1, resolve: { host: function() { return { action: n.isEdit ? "replace" : "import" } } } }] }), a.result.then(function(t) { var r, u;
                        n.isEdit = !!t.id;
                        r = n.productUnity.name;
                        n.productUnity = t;
                        r && (n.productUnity.nickName = r, n.productUnityAlias = n.productUnity.nickName.split(","));
                        n.productUnity.unityDealers = n.productUnity.unityDealers || [];
                        u = t.categoryId ? { name: t.category, id: t.categoryId } : { name: "其他", parentId: 0 };
                        n.getProductCategory(u).then(function(t) { n.productCategory = t;
                            ot(t);
                            n.productCategory.breadcrumbString = n.getCategoryBreadcrumb(t) });
                        i(function() { v();
                            n.initDealerTabScrollbar();
                            n.initPackageTabScrollbar();
                            Ares.clearError("#product-info-form") }) }), a.rendered.then(function() { n.platformModal = a;
                        u.resolve(!0) })), u.promise },
                ft = function() { Ares.validateForm(f.find("#product-info-form"), { pu_name: { required: !0 } }, { pu_name: { required: "请输入物品名称" } }) },
                et = function() { n.isProductUnitySaving || f.find("#product-info-form").valid() && (n.isProductUnitySaving = !0, n.save().then(function(t) { t == !1 && (n.isProductUnitySaving = !1);
                        Ares.sensors.track("SpuEditBasicCtrl", { PatientName: n.productUnity.name, OperationType: "保存" }) })) },
                ot = function(t) { t && t.id > 0 ? (n.productUnity.category = t.name, n.productUnity.categoryId = t.id) : (n.productUnity.category = null, n.productUnity.categoryId = null) },
                st = function() { var t = u.open({ animation: !0, backdrop: "static", template: "<product-category-select-modal-view><\/product-category-select-modal-view>", controller: "ProductCategorySelectModalCtrl", windowClass: "product-category-select-modal-wrapper", size: "md", resolve: { host: function() { return { categoryTreeData: n.categoriesTree, selectedCategory: n.productCategory, mode: "simple" } } } });
                    t.result.then(function(t) { n.productCategory = t;
                        n.productCategory.breadcrumbString = n.getCategoryBreadcrumb(t);
                        n.productUnity.category = t.name;
                        n.productUnity.categoryId = t.id }) },
                ht = function() { e.systemItemDic.loadActive().then(function(t) { if (t) { var i = _.filter(t, { itemType: "物品自由项" });
                            i && (n.freeField1 = _.find(i, { itemName: "物品自由项1" }), n.freeField2 = _.find(i, { itemName: "物品自由项2" }), n.freeField3 = _.find(i, { itemName: "物品自由项3" }));
                            n.freeField1DataSource = _.filter(t, { itemType: "物品自由项1选项" });
                            n.freeField1DataSource.unshift({ itemName: "" });
                            n.freeField2DataSource = _.filter(t, { itemType: "物品自由项2选项" });
                            n.freeField2DataSource.unshift({ itemName: "" });
                            n.freeField3DataSource = _.filter(t, { itemType: "物品自由项3选项" });
                            n.freeField3DataSource.unshift({ itemName: "" }) } }) },
                k = function() { f.find(".alias-input").focus() },
                ct = function(t) { if (t.keyCode === 13 && n.newAlias && n.newAlias.trim()) { t.preventDefault(); var i = n.newAlias && n.newAlias.replace(/^\s+|\s+$/g, "").replace(",", "，");
                        n.productUnityAlias.indexOf(i) === -1 && n.productUnityAlias.push(i);
                        n.newAlias = "" } },
                lt = function() { var t = n.newAlias && n.newAlias.replace(/^\s+|\s+$/g, "").replace(",", "，");
                    t && (n.productUnityAlias.indexOf(t) === -1 && n.productUnityAlias.push(t), n.newAlias = "");
                    k() },
                at = function(t) { n.productUnityAlias.splice(t, 1) },
                vt = function() { o.getGroupProcurementMethod().then(function(t) { t !== "group" || s.isGroup || (n.showDealerTab = !1) }) },
                yt = function(t) { switch (t) {
                        case "baseInfo":
                            n.isShowBaseInfo = !n.isShowBaseInfo;
                            v(); break;
                        case "specInfo":
                            n.isShowSpecInfo = !n.isShowSpecInfo;
                            v() } },
                p = f.find(".tab-product-unity"),
                v = function() { i(function() { var n = f.closest(".content-container").offset().top - 82;
                        p.height(angular.element(r).height() - 170 - n);
                        p.data("mCustomScrollbarIndex") ? p.mCustomScrollbar("update") : p.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) }, 0, !1) },
                pt = function() { n.productUnity.pictureId = null;
                    n.productUnity.imgUrl = null },
                y, w = function() { if (!n.productUnity.isLinkedCare && n.isRootGroup) { if (y) { i.cancel(y);
                            y = null; return } y = i(function() { var t = n.getSearchText();
                            t ? n.checkPlatformMatch().then(function(t) { t ? wt() : n.informPlatformModalNonMatch();
                                y = null }) : (n.informPlatformModalNonMatch(), y = null) }, 1e3, !1) } },
                wt = function() { return b(0).then(function() { n.sendCurrentSpuNameToPlatformModal() }) },
                bt = function(n) { n.keyCode === 13 && w() },
                d = function() { v();
                    n.initDealerTabScrollbar();
                    n.initPackageTabScrollbar();
                    n.initSalesTabScrollbar() },
                kt = function(n) { h.viewOperationLog(n.id) },
                dt = function() { var t = u.open({ animation: !0, backdrop: "static", keyboard: !1, template: "<spu-edit-certificate-upload-view><\/spu-edit-certificate-upload-view>", controller: "SpuEditCertificateUploadCtrl", windowClass: "spu-edit-certificate-upload-modal-wrapper", size: "lg", resolve: { data: function() { return { productUnityId: n.productUnity.id, certs: n.certificates && n.certificates.length > 0 ? n.certificates : n.productUnity.certificates, products: n.productUnity.products } } } });
                    t.result.then(function(t) { n.productUnity.groupedCertificates = n.groupeCertificates(t, n.productUnity.products);
                        n.certificates = t }) };
            (function() { n.selectTab = "main";
                n.isShowBaseInfo = !0;
                n.isShowSpecInfo = !0;
                n.toggleContent = yt;
                n.setTabActive = g;
                n.setEnable = nt;
                n.editSku = it;
                n.removeSku = rt;
                n.setSpecAndUnit = tt;
                n.updateProductPicture = ut;
                n.openPlatformModal = b;
                n.mainHeight = { height: $(window).height() - 180 };
                n.onSaveClick = et;
                n.openSelectProductCategoryModal = st;
                n.onAliasInputKeyPrsaveess = ct;
                n.onAliasAddBtnClick = lt;
                n.removeAlias = at;
                n.focusAliasInput = k;
                n.showDealerTab = !0;
                n.removeImg = pt;
                n.onNameChanged = w;
                n.onNameKeyUp = bt;
                n.viewOperationLog = kt;
                n.openCertificateUploadModel = dt;
                ft();
                ht();
                vt();
                n.initProducers().then(function() { n.initProductUnity().then(function() { n.initProductCategoryTreeData();
                        n.initBasicData().then(function() { v();
                            w() }) }) });
                angular.element(r).on("resize", d);
                n.$on("$destroy", function() { angular.element(r).off("resize", d) }) })() } } }]);
supplychainModule.controller("SpuEditBasicCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "aresConfirmDialog", "host", "productUnitySvc", "aresNotification", "dataDicSvc", "enums", "aresTreeViewUtil", "inventoryUtil", "officeUtil", "loginContext", "officeOptionSvc", "permissionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b) { "use strict"; var d = { id: 0, isEnabled: !0, valuationType: 0, isTakePriceSetEnabled: !1, takePriceUpRatio: 0, products: [], unityDealers: [], packages: [], productSalesPrices: [], groupedCertificates: [] },
        ft = function() { var n = []; return n.push(c.systemItemDic.loadActive({ itemType: "领用支持按百分比加价" }).then(function(n) { n && n.length > 0 && (t.isTakePriceSetEnabled = n[0].itemValue == "True", t.productUnity.isTakePriceSetEnabled = t.isTakePriceSetEnabled) })), n.push(y.isRootGroup().then(function(n) { t.isShowHandleBtn = p.isGroup && n || !p.isGroup || p.isGroup && !p.isRegularChain;
                t.isRootGroup = n })), u.all(n) },
        et = function() { return c.systemItemDic.loadActive({ itemType: "库存物品品牌" }).then(function(n) { t.producers = n }) },
        g = function() { var i = u.defer(); return t.isEdit ? s.get(o.productUnityId).success(function(n) { n.certificates && n.certificates.length > 0 && (n.groupedCertificates = ut(n.certificates, n.products));
                t.productUnity = n;
                t.productUnity.isLinkedCare && (t.productUnityAlias = t.productUnity.nickName ? t.productUnity.nickName.split(",") : []);
                n.productSalesPrices || (t.productUnity.productSalesPrices = []);
                t.productUnity.groupProductSalesPrices = n.groupProductSalesPrices ? _.filter(n.groupProductSalesPrices, function(n) { return !_.isNull(n.salesPriceUpRatio) }) : [];
                rt();
                i.resolve() }).error(function(i) { n.log(i.message);
                t.productUnity = d }) : (t.productUnity = d, t.productUnityAlias = [], i.resolve()), i.promise },
        ot = function(n) { var t = u.defer(); return c.productCategoryDic.load().then(function(i) { var r = _.find(i, n);
                r == null && (r = _.find(i, { name: "其他", parentId: 0 }));
                t.resolve(r) }), t.promise },
        st = function() { f.dismiss() },
        nt = function() { var i = u.defer(),
                n, r = !0; return t.isEdit ? p.isRootGroup ? n = s.update : (r = !1, n = s.updateOfficeProductOptions) : n = s.create, n(t.productUnity).success(function(n) { r && s.syncProductUnityMatch(n);
                t.productUnity = n;
                c.dealerDic.refresh();
                c.systemItemDic.refresh();
                c.chargeItemDic.refresh();
                ht(n).then(function(r) { r ? h.success("保存成功！") : h.error("物品保存成功，但物品证书更新失败，请尝试重新上传物品证书!");
                    t.isEdit = !0;
                    f.close(n);
                    i.resolve(!0) }) }).error(function(n) { n && (n.name === "AresBusinessException" || n.name === "ProductUnityDuplicatedException") && h.error(n.message);
                g();
                i.reject(!1) }), i.promise },
        ht = function(n) { var i = u.defer(),
                r; return t.certificates.length > 0 ? (r = [], _.forEach(t.certificates, function(t) { if (t.targetType === 1) t.targetId = n.id;
                else if (t.targetType === 2) { var i = _.find(n.products, { specAndUnit: t.targetId });
                    i ? t.targetId = i.id : r.push(t) } }), r.length > 0 && _.forEach(r, function(n) { t.certificates = _.without(t.certificates, n) }), s.updateCerts(n.id, t.certificates).success(function(n) { i.resolve(n) }).error(function() { i.resolve(!1) })) : i.resolve(!0), i.promise },
        ct = function() { var n = u.defer(); return t.productUnity ? (t.productUnity.isLinkedCare && (t.productUnity.nickName = t.productUnityAlias.join(",")), lt() ? t.productUnity.isReplacing ? e.confirm({ message: "您确定要替换该物品的信息吗？替换完成后将无法恢复到替换前物品信息。" }).then(function() { nt().then(function() { n.resolve(!0) }, function() { n.resolve(!1) }) }, function() { n.resolve(!1) }) : nt().then(function() { n.resolve(!0) }, function() { n.resolve(!1) }) : n.resolve(!1)) : n.resolve(!1), n.promise },
        lt = function() { var u, n, i, r, f; if (t.productUnity) { if (!t.productUnity.name) return h.error("请填写物品名称"), !1; if (!t.productUnity.producer) return h.error("请选择品牌"), !1; if (!t.productUnity.category || !t.productUnity.categoryId) return h.error("请选择所属类目"), !1; if (!t.productUnity.products || t.productUnity.products.length === 0) return h.error("请添加物品规格"), !1; if (u = t.productUnity.products.some(function(n) { return n.specification == "" || n.unit == "" }), u) return h.error("请填写物品规格名称和采购单位"), !1; if (t.productUnity.products.length > 1)
                    for (n = 0; n < t.productUnity.products.length - 1; n++)
                        for (i = n + 1; i < t.productUnity.products.length; i++)
                            if (t.productUnity.products[i].specification == t.productUnity.products[n].specification && t.productUnity.products[i].unit == t.productUnity.products[n].unit) return h.error("存在重复的规格"), !1; if (t.productUnity.unityDealers && t.productUnity.unityDealers.length > 0 && (r = t.productUnity.unityDealers.some(function(n) { return n.dealers == null || n.dealers.length == 0 || n.dealers.some(function(n) { return n.unit == "" || n.specification == "" || (n.price == null || n.price < 0) && n.dealerType === 0 }) }), r)) return h.error("供应商信息设置有误"), !1; if (t.productUnity.packages && t.productUnity.packages.length > 0 && (r = t.productUnity.packages.some(function(n) { return n.fromSpecification == "" || n.fromUnit == "" || n.toSpecification == "" || n.toUnit == "" || n.count <= 0 }), r)) return h.error("规格拆包设置有误"), !1; if (t.productUnity.productSalesPrices = t.productUnity.productSalesPrices || [], t.productUnity.isSalesEnabled && t.productUnity.productSalesPrices.length > 0 && (f = t.productUnity.productSalesPrices.some(function(n) { return n.productSpecAndUnit === "" || n.salesPrice === "" }), f)) return h.error("销售价信息设置有误"), !1;
                t.productUnity.productSalesPrices.length || (t.productUnity.isSalesEnabled = !1) } else return h.error("当前物品不存在"), !1; return !0 },
        at = function() { var n = u.defer(); return v.getProductCategories().then(function(i) { var r = {};
                _.each(i, function(n) { r[n.id] = n });
                t.categoryNodeMap = r;
                t.categoriesTree = a.unflatten(i, "showOrder");
                t.isEdit ? t.productCategory = _.find(i, { id: t.productUnity.categoryId }) : !t.isEdit && t.preSelectedCategory && (t.productUnity.category = t.preSelectedCategory.name, t.productUnity.categoryId = t.preSelectedCategory.id, t.productCategory = _.find(i, { id: t.preSelectedCategory.id }));
                t.productCategory && (t.productCategory.breadcrumbString = tt(t.productCategory));
                n.resolve() }), n.promise },
        tt = function(n) { for (var i = []; n;) i.push(n.name), n = t.categoryNodeMap[n.parentId]; return i.reverse().join("-") },
        vt = function() { v.getProductCodeOptions().then(function(n) { t.productCodeOptions = n }) },
        yt = function() { var n = [w.optionKeys.IsOfficePreferredDealerEnabled, w.optionKeys.IsProductUnicodeManagementEnabled]; return w.getOfficeOptions(n).then(function(n) { t.isOfficePreferredDealerEnabled = n[0];
                t.isProductUnicodeManagementEnabled = n[1] }) },
        pt = function() { f.on("CURRENT_SPU_REQUEST", function(n) { n.sourceModalId ? f.transmit("CURRENT_SPU_UPDATE", n.sourceModalId, { currentSpu: angular.copy(t.productUnity) }) : f.broadcast("CURRENT_SPU_UPDATE", { currentSpu: angular.copy(t.productUnity) }) });
            f.on("TAB_SWITCHED", function(n) { t.platformModal && t.platformModal.modalId === n.sourceModalId && n.data.tabIndex === 0 && it() }) },
        k = function() { var n = t.productUnity.name || ""; return (t.productUnity.producer && (n += " " + t.productUnity.producer), n = n.trim(), n.length < 4) ? "" : n },
        it = function() { t.platformModal && t.$modalInstance.transmit("SPU_NAME_CHANGED", t.platformModal.modalId, { searchText: k() }) },
        wt = function() { t.platformModal && !t.platformModal.destroyed && t.$modalInstance.transmit("SPU_NON_MATCH", t.platformModal.modalId, { searchText: k() }) },
        bt = function() { var n = u.defer(),
                t = k(),
                i = { pageIndex: 1, pageSize: 1, searchText: t }; return s.searchPlatformProduct(i, !0).success(function(t) { t && t.items && t.items[0] ? n.resolve(t.items[0].isMatchBaseLcSPU) : n.resolve(!1) }), n.promise },
        rt = function() { var n = t.productUnity.products;
            n && (t.productUnity.products = n.sort(function(n, t) { return n.isEnabled == t.isEnabled ? 0 : n.isEnabled ? -1 : 1 })) },
        kt = function() { var n = u.defer(); return v.getGroupProcurementConfigs().then(function(i) { t.groupSalesEnabled = i.groupSalesEnabled && p.isGroup && p.isRootGroup;
                n.resolve(!0) }), n.promise },
        dt = function() { t.productUnity.isCritical = !t.productUnity.isCritical;
            t.productUnity.unicodeGenerateMode = l.ProductUnicodeGenerateMode.None;
            t.productUnity.isReusable = !1 },
        ut = function(n, t) { var i = {},
                r = _.filter(n, function(n) { return !n.isDelete }); return _.each(r, function(n) { var r = n.code + "&&&" + n.expiredDate,
                    u;
                i[r] = i[r] || {};
                i[r].targets = i[r].targets || [];
                n.targetType === l.CertificateTargetType.ProductUnity ? i[r].targets.indexOf("所有规格") < 0 && i[r].targets.push("所有规格") : n.targetType === l.CertificateTargetType.Product && (u = _.find(t, function(t) { return t.id === n.targetId || t.specAndUnit === n.targetId }), i[r].targets.indexOf(u.specAndUnit) < 0 && i[r].targets.push(u.specAndUnit));
                i[r].certificates = i[r].certificates || [];
                i[r].certificates.push(n) }), _.map(i, function(n) { return { code: n.certificates[0].code, expiredDate: moment(n.certificates[0].expiredDate).format("YYYY-MM-DD"), description: n.certificates[0].description, target: n.targets.join(", "), images: _.uniq(_.pluck(n.certificates, "imgUrl")) } }) };
    (function() { t.certificates = [];
        t.save = ct;
        t.close = st;
        t.getProductCategory = ot;
        t.getCategoryBreadcrumb = tt;
        t.initProductUnity = g;
        t.initProductCategoryTreeData = at;
        t.sendCurrentSpuNameToPlatformModal = it;
        t.informPlatformModalNonMatch = wt;
        t.checkPlatformMatch = bt;
        t.getSearchText = k;
        t.sortProducts = rt;
        t.onIsCriticalSwitch = dt;
        t.isEdit = o.productUnityId && o.productUnityId > 0;
        t.preSelectedCategory = o.preSelectedCategory;
        t.initBasicData = ft;
        t.initProducers = et;
        t.isTakePriceSetEnabled = !1;
        t.isShowOfficeBatch = p.isGroup && p.isRootGroup;
        t.isSalesPriceEditAllowed = b.isChargeItemEditAllowed;
        t.groupeCertificates = ut;
        vt();
        pt();
        kt();
        yt() })() }]);
supplychainModule.directive("spuEditCertificateView", ["$window", "$timeout", function(n, t) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog/spu-edit-certificate-view.html", link: function(i, r) { var u = function() { var t = r.closest(".content-container").offset().top - 82;
                r.height(angular.element(n).height() - 170 - t);
                r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) };
            (function() { i.initCertificateScrollbar = u;
                t(function() { u() }, 0, !1) })() } } }]);
supplychainModule.directive("spuEditDealerView", ["$log", "$timeout", "$modal", "aresConfirmDialog", "$window", "loginContext", "officeSvc", "officeSelectorUtil", function(n, t, i, r, u, f, e, o) { "use strict"; return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog/spu-edit-dealer-view.html", scope: !1, link: function(n, s) { var l = function(r, u) { var f = i.open({ animation: !0, backdrop: "static", template: "<spu-dealer-edit-dialog-view><\/spu-dealer-edit-dialog-view>", controller: "SpuDealerEditDialogCtrl", windowClass: "spu-dealer-edit-dialog-modal-wrapper", resolve: { host: function() { return { unityDealer: angular.copy(r), skus: angular.copy(n.productUnity.products), existingDealerIds: _.map(n.productUnity.unityDealers, function(n) { return parseInt(n.dealerId) }) } } } });
                    f.result.then(function(i) { r ? n.productUnity.unityDealers[u] = i : (n.productUnity.unityDealers.length === 0 && (i.isPreferred = !0), n.productUnity.unityDealers.push(i));
                        t(function() { c() }, 0, !1) }) },
                a = function(t) { _.each(n.productUnity.unityDealers, function(n) { n.isPreferred = !1 });
                    t.isPreferred = !0 },
                h = s.find(".spu-edit-dealer-body"),
                c = function() { var n = s.closest(".content-container").offset().top - 82;
                    h.height(angular.element(u).height() - 170 - n);
                    h.data("mCustomScrollbarIndex") ? h.mCustomScrollbar("update") : h.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) },
                v = function(t) { r.confirm({ message: "确定删除此供应商？" }).then(function() { n.productUnity.unityDealers.splice(t, 1) }) },
                y = function() { return e.getSelfAndChildOfficesByGroupId(f.officeId, !1).success(function(t) { var i = o.setId(t);
                        n.allOfficeIds = [];
                        n.officeTreeData = i }) },
                p = function(t) { t && (t.preferredOfficeIds || (t.preferredOfficeIds = []), y().then(function() { var i = { officeTreeData: n.officeTreeData, selectMode: "officeOnly", checkbox: !0, title: "选择机构", allowNoneSelection: !0, selectedOfficeIds: t.preferredOfficeIds };
                        o.open(i).then(function(n) { var i = _.map(n, function(n) { return parseInt(n.officeId) });
                            t.preferredOfficeIds.sort().toString() !== i.sort().toString() && r.confirm({ message: "确定修改配置机构？" }).then(function() { t.preferredOfficeIds = i }) }) })) };
            (function() { n.openEditSpuDealerModal = l;
                n.onPreferredDealerChanged = a;
                n.initDealerTabScrollbar = c;
                n.removeDealer = v;
                n.openPreferredOfficeDialog = p;
                t(function() { c() }, 0, !1) })() } } }]);
supplychainModule.directive("spuEditGroupSalesPriceView", ["$log", "$timeout", "$modal", "$window", function(n, t, i, r) { "use strict"; return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog/spu-edit-group-sales-price-view.html", scope: !1, link: function(n, u) { var e = function() { var r = i.open({ animation: !0, backdrop: "static", template: "<spu-group-sales-price-edit-dialog-view><\/spu-group-sales-price-edit-dialog-view>", controller: "SpuGroupSalesPriceEditDialogCtrl", windowClass: "spu-group-sales-price-edit-dialog-modal-wrapper", size: "md", resolve: { host: function() { return { groupSalesPrices: angular.copy(n.productUnity.groupProductSalesPrices), skus: angular.copy(n.productUnity.products) } } } });
                    r.result.then(function(i) { n.productUnity.groupProductSalesPrices = i;
                        t(function() { f() }, 0, !1) }) },
                f = function() { var n = u.closest(".content-container").offset().top - 82;
                    u.height(angular.element(r).height() - 170 - n);
                    u.data("mCustomScrollbarIndex") ? u.mCustomScrollbar("update") : u.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) };
            (function() { n.openGroupSalesPriceDialog = e;
                n.initSalesTabScrollbar = f;
                t(function() { f() }, 0, !1) })() } } }]);
supplychainModule.directive("spuEditPackageView", ["$log", "$timeout", "$modal", "aresDialog", "$window", "inventoryProductSvc", "$q", "aresModalShelf", "aresConfirmDialog", "officeSvc", "loginContext", "moduleOptionProvider", "officeSelectorUtil", "enums", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { "use strict"; return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog/spu-edit-package-view.html", scope: !1, link: function(n, i) { var w = function() { var i = n.$shelfInstance.open({ title: "新增拆包关系", titleIconFont: "iconfont icon-chaibaoguoqujian-xianxing", template: "<spu-edit-package-modal-view><\/spu-edit-package-modal-view>", controller: "SpuEditPackageModalCtrl", needActive: !0, resolve: { host: function() { return { skus: angular.copy(n.productUnity.products), packages: angular.copy(n.productUnity.packages) } } } });
                    i.result.then(function(i) { n.productUnity.products = n.productUnity.products.concat(i.newSkus);
                        n.productUnity.packages = n.productUnity.packages.concat(i.newPackages);
                        t(function() { y();
                            r() }, 0, !1) }) },
                l = function() { var i = e.defer(),
                        u; return n.productUnity.id ? (u = _.filter(_.pluck(n.productUnity.products, "id"), function(n) { return n > 0 }), f.searchInventoryProductBatch({ productIds: u }).success(function(u) { u = _.filter(u, function(n) { return n.count > 0 });
                        u = _.sortBy(u, "warehouseId");
                        u && u.length > 0 ? h.getOfficeList().success(function(f) { f.length > 1 ? i.resolve(!0) : (i.reject(!1), s.warn({ message: "当前物品已有库存，是否打开配置页继续修改？", showCancelBtn: !0 }).then(function() { var i = o.open({ title: "分批与计价方式管理", template: "<spu-edit-batch-exp-modal-view><\/spu-edit-batch-exp-modal-view>", controller: "SpuEditBatchExpModalCtrl", resolve: { host: function() { return { productUnityId: n.productUnity.id, batches: u, isBatchNoEnabled: n.productUnity.isBatchNoEnabled, isExpiredDateEnabled: n.productUnity.isExpiredDateEnabled, valuationType: n.productUnity.valuationType } } }, needActive: !0, confirmClose: !0 });
                                i.result.then(function(i) { i && (n.productUnity.isBatchNoEnabled = i.isBatchNoEnabled, n.productUnity.isExpiredDateEnabled = i.isExpiredDateEnabled, n.productUnity.valuationType = i.valuationType);
                                    t(function() { r() }, 0, !1) }) }).catch(function() { i.reject(!1) })) }) : i.resolve(!0) })) : i.resolve(!0), i.promise },
                b = function() { l().then(function() { n.productUnity && (n.productUnity.isBatchNoEnabled = !n.productUnity.isBatchNoEnabled, n.productUnity.unicodeGenerateMode = v.ProductUnicodeGenerateMode.None);
                        t(function() { r() }, 0, !1) }) },
                k = function() { l().then(function() { n.productUnity && (n.productUnity.isExpiredDateEnabled = !n.productUnity.isExpiredDateEnabled, n.productUnity.unicodeGenerateMode = v.ProductUnicodeGenerateMode.None);
                        t(function() { r() }, 0, !1) }) },
                d = function(t) { l().then(function() { n.productUnity && (n.productUnity.valuationType = t) }) },
                g = function(t) { n.productUnity.unicodeGenerateMode == v.ProductUnicodeGenerateMode.None && t > v.ProductUnicodeGenerateMode.None && n.productUnity.packages && n.productUnity.packages.length > 0 ? s.confirm({ message: "如果开启条码管理, 将清除拆包关系？" }).then(function() { n.productUnity.unicodeGenerateMode = t }) : n.productUnity.unicodeGenerateMode = t;
                    t == v.ProductUnicodeGenerateMode.None && (n.productUnity.isReusable = !1) },
                r = function() { var n = i.closest(".content-container").offset().top - 82;
                    i.height(angular.element(u).height() - 170 - n);
                    i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) },
                y = function() { t(function() { i.find("[data-toggle=tooltip]").tooltip() }, 0, !1) },
                nt = function(t) { n.productUnity.packages.splice(t, 1) },
                tt = function(t) { n.productUnity.packages[t].isEditing = !0 },
                it = function() { return h.getSelfAndChildOfficesByGroupId(c.officeId, !1).success(function(t) { var i = a.setId(t),
                            r = [];
                        p(i, r);
                        n.allOfficeIds = r;
                        n.officeTreeData = i }) },
                p = function(n, t) { _.each(n, function(n) { t.push(n.id);
                        n.isGroup && n.parentId !== 0 && (n.isGroup = !1);
                        n.hasChildren && p(n.items, t) }) },
                rt = function() { it().then(function() { var i = [],
                            u, r;
                        i.push(c.officeId);
                        _.each(n.allOfficeIds, function(t) { i.indexOf(t) !== -1 || n.productUnity.notAvailableOfficeIds && n.productUnity.notAvailableOfficeIds.indexOf(t) !== -1 || i.push(t) });
                        u = { officeTreeData: n.officeTreeData, selectMode: "officeOnly", checkbox: !0, title: "选择机构", allowNoneSelection: !0, selectedOfficeIds: i };
                        r = [];
                        a.open(u).then(function(t) { var u = _.map(t, function(n) { return parseInt(n.officeId) });
                            (u.push(c.officeId), i.sort().toString() !== u.sort().toString()) && s.confirm({ message: "确定修改可见机构？" }).then(function() { _.each(n.allOfficeIds, function(n) { u.indexOf(n) === -1 && r.push(n) });
                                n.productUnity.notAvailableOfficeIds = r }) });
                        t(function() { angular.element.find(".office-selector-dialog-modal-wrapper div.k-top.k-bot input[type=checkbox]")[0].checked = !0 }, 100) }) },
                ut = function() { n.productUnity.isReusable = !n.productUnity.isReusable };
            (function() { n.showPackageEditModal = w;
                n.onBatchManagementSwitch = b;
                n.onExpireDateWarnSwitch = k;
                n.initPackageTabScrollbar = r;
                n.onDeletePackage = nt;
                n.onEditPackage = tt;
                n.initPackageTabTooltip = y;
                n.onValuationTypeSwitch = d;
                n.openUpdateOfficeDialog = rt;
                n.onUnicodeGenerateModeSwitch = g;
                n.setIsReusable = ut;
                t(function() { r() }, 0, !1) })() } } }]);
supplychainModule.directive("spuEditSalePriceView", ["$log", "$timeout", "$modal", "$window", function(n, t, i, r) { "use strict"; return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog/spu-edit-sale-price-view.html", scope: !1, link: function(n, u) { var e = function() { n.productUnity && (n.productUnity.isSalesEnabled = !n.productUnity.isSalesEnabled) },
                o = function() { var r = i.open({ animation: !0, backdrop: "static", template: "<spu-sales-price-edit-dialog-view><\/spu-sales-price-edit-dialog-view>", controller: "SpuSalesPriceEditDialogCtrl", windowClass: "spu-sales-price-edit-dialog-modal-wrapper", size: "md", resolve: { host: function() { return { salesPrices: angular.copy(n.productUnity.productSalesPrices), skus: angular.copy(n.productUnity.products) } } } });
                    r.result.then(function(i) { n.productUnity.productSalesPrices = i;
                        t(function() { f() }, 0, !1) }) },
                f = function() { var n = u.closest(".content-container").offset().top - 82;
                    u.height(angular.element(r).height() - 170 - n);
                    u.data("mCustomScrollbarIndex") ? u.mCustomScrollbar("update") : u.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) };
            (function() { n.setSalesEnable = e;
                n.openSalePriceDialog = o;
                n.initSalesTabScrollbar = f;
                t(function() { f() }, 0, !1) })() } } }]);
supplychainModule.directive("skuEditFormView", ["inventoryUtil", "dataDicSvc", "$timeout", "aresConfirmDialog", function(n, t, i, r) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/sku-edit-form-view.html", scope: { sku: "=", batchMode: "=", readOnly: "=" }, link: function(i) { var u = function() { n.getProductCodeOptions().then(function(n) { i.baseData.productCodeOptions = n }) },
                f = function() { t.systemItemDic.loadActive({ itemType: "库存物品单位" }).then(function(n) { i.baseData.units = n }) },
                e = function() { t.systemItemDic.loadActive().then(function(n) { if (n) { var t = _.filter(n, { itemType: "物品自由项" });
                            t && (i.baseData.freeField1 = _.find(t, { itemName: "物品自由项1" }), i.baseData.freeField2 = _.find(t, { itemName: "物品自由项2" }), i.baseData.freeField3 = _.find(t, { itemName: "物品自由项3" }));
                            i.baseData.freeField1DataSource = _.filter(n, { itemType: "物品自由项1选项" });
                            i.baseData.freeField1DataSource.unshift({ itemName: "" });
                            i.baseData.freeField2DataSource = _.filter(n, { itemType: "物品自由项2选项" });
                            i.baseData.freeField2DataSource.unshift({ itemName: "" });
                            i.baseData.freeField3DataSource = _.filter(n, { itemType: "物品自由项3选项" });
                            i.baseData.freeField3DataSource.unshift({ itemName: "" }) } }) },
                o = function(n) { n.specAndUnit = n.specification + "(" + n.unit + ")" },
                s = function(t) { var i = function() { t.isEnabled = !t.isEnabled };
                    t.isEnabled && t.id > 0 ? n.checkProductInventoryCount([t.id]).then(function(n) { n.data ? r.confirm({ message: "该物品/规格仍然有库存，系统将不允许该物品进行采购和入库，但仍然允许执行出库操作。确定禁用该物品/规格吗？" }).then(function() { i() }, function() {}) : i() }) : i() };
            (function() { i.baseData = {};
                i.setSpecAndUnit = o;
                i.setEnable = s;
                u();
                f();
                e() })() } } }]);
supplychainModule.directive("skuEditView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", function(n, t) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/sku-edit-view.html", link: function(n, i) {
            (function() { t(function() { Ares.centerModal(i.closest(".modal-dialog")) }, 100, !1) })() } } }]);
supplychainModule.controller("skuEditCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "host", "inventoryUtil", "dataDicSvc", "aresNotification", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var c = function() { f.dismiss() },
        l = function() { t.skus = e.skus;
            e.sku ? (t.sku = _.clone(e.sku), t.isEdit = !0) : t.sku = { id: 0, isLinkedCare: !1, specification: "", unit: "", specAndUnit: "", factoryLocation: "", producerBarCode: "", producerCode: "", code: "", freeField1: "", freeField2: "", freeField3: "", isEnabled: !0 } },
        a = function() { if (!t.sku.specification) { h.error("请填写规格名称"); return } if (!t.sku.unit) { h.error("请填写单位"); return } if (!t.isEdit) { var n = _.any(t.skus, function(n) { return n.specification === t.sku.specification && n.unit === t.sku.unit }); if (n) { h.error("已存在相同的规格单位"); return } } t.sku.specAndUnit = t.sku.specification + "(" + t.sku.unit + ")";
            f.close(t.sku) };
    (function() { l();
        t.closeThePopup = c;
        t.onSave = a })() }]);
supplychainModule.directive("skuPackageEditDialogView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", function(n, t, i, r, u) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/sku-package-edit-dialog-view.html", link: function(n, i) { var e = function(i, r, f) { var e = i.sender.dataItem(i.item.index()),
                        o; if (e.specAndUnit !== "请选择规格") { if (o = _.any(n.packages, function(n) { return f === "from" && n.fromSpecAndUnit === e.specAndUnit }), o) { u.error("当前拆包规格已存在");
                            t(function() { i.sender.value(0);
                                r.fromProductId = 0;
                                r.fromSpecification = "";
                                r.fromUnit = 0;
                                r.fromSpecAndUnit = "请选择规格" }); return } if (f === "to" && r.fromSpecAndUnit === e.specAndUnit || f === "from" && r.toSpecAndUnit === e.specAndUnit) { u.error("相同规格单位不能进行拆包");
                            t(function() { i.sender.value(0);
                                f === "from" ? (r.fromProductId = 0, r.fromSpecification = "", r.fromUnit = 0, r.fromSpecAndUnit = "请选择规格") : f === "to" && (r.toProductId = 0, r.toSpecification = "", r.toUnit = 0, r.toSpecAndUnit = "请选择规格") }); return } if (f === "to" && r.fromUnit === e.unit || f === "from" && r.toUnit === e.unit) { u.error("相同单位不能进行拆包");
                            t(function() { i.sender.value(0);
                                f === "from" ? (r.fromProductId = 0, r.fromSpecification = "", r.fromUnit = 0, r.fromSpecAndUnit = "请选择规格") : f === "to" && (r.toProductId = 0, r.toSpecification = "", r.toUnit = 0, r.toSpecAndUnit = "请选择规格") }); return } t(function() { f === "from" ? (r.fromProductId = e.id, r.fromSpecification = e.specification, r.fromUnit = e.unit, r.fromSpecAndUnit = e.specAndUnit) : f === "to" && (r.toProductId = e.id, r.toSpecification = e.specification, r.toUnit = e.unit, r.toSpecAndUnit = e.specAndUnit) }) } },
                r = i.find(".sku-content"),
                f = function() { r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } }) };
            (function() { n.onSelectSku = e;
                n.initScrollbar = f;
                t(function() { Ares.centerModal(i.closest(".modal-dialog"));
                    f() }, 100) })() } } }]);
supplychainModule.controller("SkuPackageEditDialogCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "host", "inventoryUtil", "aresNotification", function(n, t, i, r, u, f, e, o, s) { "use strict"; var c = function() { f.dismiss() },
        l = function() { var n = e.skus || [];
            n.unshift({ productId: 0, specAndUnit: "请选择规格" });
            t.skus = n;
            t.packages = e.packages || [];
            t.packages.length === 0 && h() },
        a = function() { var i = _.any(t.packages, function(n) { return !n.fromSpecAndUnit || !n.toSpecAndUnit || n.fromSpecAndUnit === "请选择规格" || n.toSpecAndUnit === "请选择规格" }),
                n; if (i) { s.error("请选择规格"); return } if (n = _.any(t.packages, function(n) { return !n.count }), n) { s.error("请填写拆包数量"); return } f.close(t.packages) },
        h = function() { t.packages.push({ count: 0, fromProductId: 0, fromSpecification: "", fromUnit: "", fromSpecAndUnit: "请选择规格", toProductId: 0, toSpecification: "", toUnit: "", toSpecAndUnit: "请选择规格" });
            r(function() { t.initScrollbar() }, 0, !1) },
        v = function(n) { t.packages.splice(n, 1) };
    (function() { l();
        t.closeThePopup = c;
        t.onSave = a;
        t.addItem = h;
        t.remove = v })() }]);
supplychainModule.directive("spuDealerEditDialogView", ["$log", "$timeout", "$window", "aresNotification", "aresDialog", function(n, t, i, r) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/spu-dealer-edit-dialog-view.html", link: function(n, i) { var e = function(t) { var i = t.sender.dataItem(t.item.index());
                    n.unityDealer.dealerName = i.name },
                o = function(i, u) { var f = i.sender.dataItem(i.item.index()),
                        o, e; if (f.specAndUnit !== "请选择规格") { if (o = n.unityDealer.dealers.some(function(n) { return n.specAndUnit === f.specAndUnit }), o) return r.error("当前规格报价已经存在！"), t(function() { i.sender.value(0);
                            u.productId = 0;
                            u.specification = "";
                            u.unit = "";
                            u.specAndUnit = "请选择规格" }), !1;
                        u.productId = f.id;
                        u.name = f.name;
                        u.producer = f.producer;
                        u.specification = f.specification;
                        u.unit = f.unit;
                        u.specAndUnit = f.specification + "(" + f.unit + ")";
                        u.selected = !0;
                        n.refreshSkus();
                        e = u.kendoDropDownList;
                        e.destroy();
                        e.wrapper.remove() } },
                u = i.find(".sku-content"),
                f = function(n) { u.data("mCustomScrollbarIndex") ? u.mCustomScrollbar("update") : u.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                    n && u.mCustomScrollbar("scrollTo", "bottom") };
            (function() { n.onSelectDealer = e;
                n.onSelectSku = o;
                n.initScrollbar = f;
                t(function() { f();
                    Ares.centerModal(i.closest(".modal-dialog")) }, 100) })() } } }]);
supplychainModule.controller("SpuDealerEditDialogCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "host", "inventoryUtil", "dataDicSvc", "aresNotification", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var l = function() { f.dismiss() },
        a = function() { s.dealerDic.loadActive().then(function(n) { var i;
                i = t.isEdit ? _.filter(n, function(n) { return n.type === 0 && n.id != -100 && (t.unityDealer.dealerId == n.id || t.existingDealerIds.indexOf(n.id) < 0) }) : _.filter(n, function(n) { return n.type === 0 && n.id != -100 && t.existingDealerIds.indexOf(n.id) < 0 });
                i.unshift({ id: 0, name: "请选择供应商" });
                t.dealers = i }) },
        v = function() { e.unityDealer ? (t.isEdit = !0, t.unityDealer = e.unityDealer, _.each(t.unityDealer.dealers, function(n) { n.selected = !0;
                n.price = parseFloat(n.price);
                _.isNaN(n.price) && (n.price = 0);
                n.price = n.price.toFixed(2) })) : t.unityDealer = { dealerId: 0, dealers: [{ productId: 0, price: "0.00", specAndUnit: "请选择规格" }], isLinkedcare: !1, isPreferred: !1 };
            c() },
        y = function() { t.unityDealer.dealers.push({ productId: 0, price: "0.00", specAndUnit: "请选择规格" });
            r(function() { t.initScrollbar(!0) }, 0, !1) },
        p = function(n) { t.unityDealer.dealers.splice(n, 1);
            t.refreshSkus();
            r(function() { t.initScrollbar() }, 0, !1) },
        w = function() { if (!t.unityDealer.dealerId) { h.error("请选择供应商"); return } if (t.unityDealer.dealers.length === 0) { h.error("请添加规格"); return } var n = _.some(t.unityDealer.dealers, function(n) { return n.specAndUnit === "请选择规格" }); if (n) { h.error("请选择规格"); return } _.each(t.unityDealer.dealers, function(n) { delete n.kendoDropDownList });
            f.close(t.unityDealer) },
        c = function() { var n = _.pluck(t.unityDealer.dealers, "productId"),
                i = _.pluck(t.unityDealer.dealers, "specAndUnit");
            t.skus = _.filter(t.cachedSkus, function(t) { return t.id ? n.indexOf(t.id) < 0 : t.specAndUnit === "请选择规格" || i.indexOf(t.specAndUnit) < 0 }) };
    (function() { var n = e.skus || [];
        n.unshift({ id: 0, specAndUnit: "请选择规格" });
        t.cachedSkus = angular.copy(n);
        t.existingDealerIds = e.existingDealerIds || [];
        v();
        a();
        t.closeThePopup = l;
        t.addNew = y;
        t.remove = p;
        t.onSave = w;
        t.refreshSkus = c })() }]);
supplychainModule.directive("spuEditCertificateUploadView", ["$window", "$timeout", function() { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/spu-edit-certificate-upload-view.html", link: function() {
            (function() {})() } } }]);
supplychainModule.controller("SpuEditCertificateUploadCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "data", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var s = { type: 1, create: function(n) { var t = { code: "", name: "", description: "", expiredDate: "", certs: [], targetId: e.productUnityId, targetType: 1, isDelete: !1, certificateId: 0 }; return n && n.length > 0 && (t.code = n[0].code, t.name = n[0].name, t.description = n[0].description, t.expiredDate = n[0].expiredDate, _.forEach(n, function(n) { t.certs.push({ certificateId: n.certificateId, pictureId: n.pictureId, imgUrl: n.imgUrl, isDelete: !1 });
                    n.certificateId > 0 && (t.certificateId = n.certificateId) })), t } },
        l = { type: 2, create: function(n) { var t = { code: "", name: "", description: "", expiredDate: "", selectedSpecs: [], certs: [], pictures: [], targetType: 2, isDelete: !1 },
                    i, r; if (n && n.length > 0) { t.code = n[0].code;
                    t.name = n[0].name;
                    t.description = n[0].description;
                    t.expiredDate = n[0].expiredDate; var u = _.pluck(_.filter(n, function(n) { return !_.isString(n.targetId) && n.targetId > 0 }), "targetId"),
                        f = _.pluck(_.filter(n, function(n) { return !_.isEmpty(n.targetId) && _.isString(n.targetId) }), "targetId"),
                        o = _.filter(e.products, function(n) { return _.contains(u, n.id) || _.contains(f, n.specAndUnit) });
                    t.selectedSpecs = _.pluck(o, "specAndUnit");
                    _.forEach(n, function(n) { t.certs.push({ certificateId: n.certificateId, targetId: _.isString(n.targetId) ? n.targetId : _.find(e.products, { id: n.targetId }).specAndUnit, imgUrl: n.imgUrl, pictureId: n.pictureId, isDelete: !1 });
                        n.certificateId > 0 && (t.certificateId = n.certificateId) });
                    i = _.groupBy(n, function(n) { return n.imgUrl }); for (const n in i)
                        if (i.hasOwnProperty(n)) { const u = i[n];
                            r = _.first(u);
                            r && t.pictures.push(_.pick(r, ["pictureId", "imgUrl"])) } } return t } },
        h = function(n) { var t = function(t) { n.targetType === s.type ? n.certs.push({ certificateId: 0, pictureId: t.id, imgUrl: t.filePath, isDelete: !1 }) : n.pictures.push({ pictureId: t.id, imgUrl: t.filePath }) },
                i = function(t) { if (n.targetType === s.type) { var i = n.certs[t];
                        i.certificateId > 0 ? i.isDelete = !0 : n.certs.splice(t, 1) } else n.pictures.splice(t, 1) };
            n.onPicSaved = t;
            n.deletePic = i },
        y = function() { var f = _.groupBy(e.certs, "targetType"),
                i = _.groupBy(f[1], function(n) { return n.code + n.expiredDate + n.description }),
                r, n, u; for (const n in i) i.hasOwnProperty(n) && (r = s.create(i[n]), h(r), t.certGroups.spu.push(r));
            n = _.groupBy(f[2], function(n) { return n.code + n.expiredDate + n.description }); for (const i in n) n.hasOwnProperty(i) && (u = l.create(n[i]), h(u), t.certGroups.sku.push(u));
            _.isEmpty(t.certGroups.sku) && v();
            _.isEmpty(t.certGroups.spu) && a() },
        a = function() { var n = s.create();
            h(n);
            t.certGroups.spu.push(n) },
        v = function() { var n = l.create();
            h(n);
            t.certGroups.sku.push(n) },
        p = function(n, t, i) { var u = _.find(t.certs, function(n) { return n.certificateId > 0 }),
                r;
            u ? t.isDelete = !0 : n.splice(i, 1);
            r = $("#specSelecter-" + i).data("kendoMultiSelect");
            r && r.destroy && r.destroy() },
        w = function() { f.dismiss() },
        b = function() { var n = d();
            k(n) || (_.forEach(n, function(n) { n.description = n.name }), f.close(n)) },
        k = function(n) { var t = !1; return t = _.some(_.filter(n, { isDelete: !1 }), function(n) { return _.isEmpty(n.code.trim()) || _.isEmpty(n.name.trim()) || _.isEmpty(n.expiredDate.trim()) || !n.pictureId || n.pictureId <= 0 }), t && o.error("请完善证书字段"), t },
        d = function() { var n = []; return _.forEach(t.certGroups.spu, function(t) { var i;
                t.isDelete ? (i = _.filter(t.certs, function(n) { return n.certificateId > 0 }), _.forEach(i, function(i) { var r = _.assign(_.omit(_.clone(t), ["certs", "isDelete"]), i);
                    r.isDelete = !0;
                    n.push(r) })) : (i = _.filter(t.certs, function(n) { return n.certificateId > 0 || !n.isDelete }), _.forEach(i, function(i) { var r = _.assign(_.omit(_.clone(t), ["certs", "isDelete"]), i);
                    n.push(r) })) }), _.forEach(t.certGroups.sku, function(t) { if (t.isDelete) { var i = _.filter(t.certs, function(n) { return n.certificateId > 0 });
                    _.forEach(i, function(i) { i.isDelete = !0;
                        n.push(c(t, i)) }) } else _.forEach(t.certs, function(i) { var r = _.find(t.selectedSpecs, function(n) { return i.targetId === n }) && _.find(t.pictures, function(n) { return n.imgUrl === i.imgUrl });
                    r || (i.isDelete = !0);
                    n.push(c(t, i)) }), _.forEach(t.pictures, function(i) { _.forEach(t.selectedSpecs, function(r) { var u = _.find(n, function(n) { return n.targetId === r && i.imgUrl === n.imgUrl });
                        u || n.push(c(t, { certificateId: 0, targetId: r, imgUrl: i.imgUrl, pictureId: i.pictureId, isDelete: !1 })) }) }) }), n },
        c = function(n, t) { var i = _.assign(_.omit(_.clone(n), ["certs", "isDelete", "selectedSpecs", "pictures"]), t); return i.certificateId = n.certificateId, i };
    (function() { t.products = e.products;
        t.certGroups = { spu: [], sku: [] };
        t.addSpuCertGroup = a;
        t.addSkuCertGroup = v;
        t.deleteCertGroup = p;
        t.close = w;
        t.ok = b;
        y() })() }]);
supplychainModule.directive("spuGroupSalesPriceEditDialogView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", function(n, t, i, r, u) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/spu-group-sales-price-edit-dialog-view.html", link: function(n, i) { var e = function(i, r) { var f = i.sender.dataItem(i.item.index()),
                        o, e; if (f.specAndUnit !== "请选择规格") { if (o = n.groupSalesPrices.some(function(n) { return n.productSpecAndUnit === f.specification + "(" + f.unit + ")" }), o) return u.error("当前规格已设置加价百分比！"), t(function() { i.sender.value(0);
                            r.productId = 0;
                            r.productUnit = "";
                            r.productSpecAndUnit = "请选择规格";
                            r.productSpecification = "" }), !1;
                        r.productId = f.id;
                        r.productUnit = f.unit;
                        r.productSpecification = f.specification;
                        r.productSpecAndUnit = f.specification + "(" + f.unit + ")";
                        r.selected = !0;
                        n.refreshSkus();
                        e = r.kendoDropDownList;
                        e.destroy();
                        e.wrapper.remove() } },
                r = i.find(".sku-content"),
                f = function(n) { r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                    n && r.mCustomScrollbar("scrollTo", "bottom") };
            (function() { n.onSelectSku = e;
                n.initScrollbar = f;
                t(function() { Ares.centerModal(i.closest(".modal-dialog"));
                    f() }, 100) })() } } }]);
supplychainModule.controller("SpuGroupSalesPriceEditDialogCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "host", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var h = function() { f.dismiss() },
        c = function() { var n = e.skus || [];
            n.unshift({ productId: 0, specAndUnit: "请选择规格" });
            t.cachedSkus = n;
            t.skus = angular.copy(n);
            t.groupSalesPrices = _.isArray(e.groupSalesPrices) && e.groupSalesPrices.length > 0 ? _.map(e.groupSalesPrices, function(n) { return n.selected = !0, n.salesPriceUpRatio = parseInt(n.salesPriceUpRatio), _.isNaN(n.salesPriceUpRatio) && (n.salesPriceUpRatio = 0), n }) : [{ productId: 0, salesPriceUpRatio: 0, productSpecAndUnit: "请选择规格" }];
            s() },
        l = function(n) { t.groupSalesPrices.splice(n, 1);
            s() },
        a = function() { t.groupSalesPrices.push({ productId: 0, salesPriceUpRatio: 0, productSpecAndUnit: "请选择规格" });
            r(function() { t.initScrollbar(!0) }) },
        v = function() { var n = _.any(t.groupSalesPrices, function(n) { return n.productSpecAndUnit === "请选择规格" }); if (n) { o.error("请选择规格"); return } _.each(t.groupSalesPrices, function(n) { delete n.kendoDropDownList });
            f.close(t.groupSalesPrices) },
        s = function() { var n = _.pluck(t.groupSalesPrices, "productSpecAndUnit");
            t.skus = _.filter(t.cachedSkus, function(t) { return t.specAndUnit === "请选择规格" || n.indexOf(t.specAndUnit) < 0 }) };
    (function() { c();
        t.closeThePopup = h;
        t.remove = l;
        t.addItem = a;
        t.onSave = v;
        t.refreshSkus = s })() }]);
supplychainModule.directive("spuSalesPriceEditDialogView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", function(n, t, i, r, u) { "use strict"; return { replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-dialog-modals/spu-sales-price-edit-dialog-view.html", link: function(n, i) { var e = function(i, r) { var f = i.sender.dataItem(i.item.index()),
                        o, e; if (f.specAndUnit !== "请选择规格") { if (o = n.salesPrices.some(function(n) { return n.productSpecAndUnit === f.specification + "(" + f.unit + ")" }), o) return u.error("当前规格销售价已经存在！"), t(function() { i.sender.value(0);
                            r.productId = 0;
                            r.productUnit = "";
                            r.productSpecAndUnit = "请选择规格";
                            r.productSpecification = "" }), !1;
                        r.productId = f.id;
                        r.productUnit = f.unit;
                        r.productSpecification = f.specification;
                        r.productSpecAndUnit = f.specification + "(" + f.unit + ")";
                        r.selected = !0;
                        n.refreshSkus();
                        e = r.kendoDropDownList;
                        e.destroy();
                        e.wrapper.remove() } },
                r = i.find(".sku-content"),
                f = function(n) { r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                    n && r.mCustomScrollbar("scrollTo", "bottom") };
            (function() { n.onSelectSku = e;
                n.initScrollbar = f;
                t(function() { Ares.centerModal(i.closest(".modal-dialog"));
                    f() }, 100) })() } } }]);
supplychainModule.controller("SpuSalesPriceEditDialogCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "$modalInstance", "host", "aresNotification", function(n, t, i, r, u, f, e, o) { "use strict"; var h = function() { f.dismiss() },
        c = function() { var n = e.skus || [];
            n.unshift({ productId: 0, specAndUnit: "请选择规格" });
            t.cachedSkus = n;
            t.skus = angular.copy(n);
            t.salesPrices = _.isArray(e.salesPrices) && e.salesPrices.length > 0 ? _.map(e.salesPrices, function(n) { return n.selected = !0, n.salesPrice = parseFloat(n.salesPrice), _.isNaN(n.salesPrice) && (n.salesPrice = 0), n.salesPrice = n.salesPrice.toFixed(2), n }) : [{ productId: 0, salesPrice: "0.00", productSpecAndUnit: "请选择规格", isSalesEnabled: !0 }];
            s() },
        l = function(n) { t.salesPrices.splice(n, 1);
            s() },
        a = function() { t.salesPrices.push({ productId: 0, salesPrice: "0.00", productSpecAndUnit: "请选择规格", isSalesEnabled: !0 });
            r(function() { t.initScrollbar(!0) }) },
        v = function() { var n = _.any(t.salesPrices, function(n) { return n.productSpecAndUnit === "请选择规格" }); if (n) { o.error("请选择规格"); return } _.each(t.salesPrices, function(n) { delete n.kendoDropDownList });
            f.close(t.salesPrices) },
        s = function() { var n = _.pluck(t.salesPrices, "productId"),
                i = _.pluck(t.salesPrices, "productSpecAndUnit");
            t.skus = _.filter(t.cachedSkus, function(t) { return t.id ? n.indexOf(t.id) < 0 : t.specAndUnit === "请选择规格" || i.indexOf(t.specAndUnit) < 0 }) };
    (function() { c();
        t.closeThePopup = h;
        t.remove = l;
        t.addItem = a;
        t.onSave = v;
        t.refreshSkus = s })() }]);
supplychainModule.directive("spuEditPackageModalView", ["$timeout", "$window", function(n, t) { "use strict"; return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-edit-package-modal/spu-edit-package-modal-view.html", link: function(i, r) { var e = function(t, r, u) { r === "from" && u === "select" ? (i.packageRules[t].isFromSkuNew = !1, i.packageRules[t].fromSku = { specAndUnit: "请选择规格" }, i.packageRules[t].isFromSkuToBeSelected = !0) : r === "from" && u === "add" ? (i.packageRules[t].isFromSkuNew = !0, i.packageRules[t].fromSku = i.generateNewSku(i.packageRules[t].toSku, ""), i.packageRules[t].isFromSkuToBeSelected = !1) : r === "to" && u === "select" ? (i.packageRules[t].isToSkuNew = !1, i.packageRules[t].toSku = { specAndUnit: "请选择规格" }, i.packageRules[t].isToSkuToBeSelected = !0) : r === "to" && u === "add" && (i.packageRules[t].isToSkuNew = !0, i.packageRules[t].toSku = i.generateNewSku(i.packageRules[t].fromSku, ""), i.packageRules[t].isToSkuToBeSelected = !1);
                    n(function() { f() }) },
                o = function(n, t, r) { var u = n.sender.dataItem(n.item.index()),
                        f, e;
                    r === "from" ? (i.packageRules[t].fromSku = u, i.editType === "batch" ? i.packageRules[t].isFromSkuToBeSelected = !1 : i.editType === "single" && i.packageRules[0].toSku.specAndUnit === "请选择规格" && (f = _.find(i.skus, function(n) { return n.specification === u.specification && n.unit !== u.unit }), f && (i.packageRules[t].toSku = f))) : r === "to" && (i.packageRules[t].toSku = u, i.editType === "batch" ? i.packageRules[t].isToSkuToBeSelected = !1 : i.editType === "single" && i.packageRules[0].fromSku.specAndUnit === "请选择规格" && (e = _.find(i.skus, function(n) { return n.specification === u.specification && n.unit !== u.unit }), e && (i.packageRules[t].fromSku = e))) },
                u = r.find(".content-body"),
                f = function() { var n = angular.element(t).height() - 265;
                    i.editType === "batch" && (n -= 50);
                    u.height(n);
                    u.data("mCustomScrollbarIndex") ? u.mCustomScrollbar("update") : u.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) },
                s = function() { i.editType === "batch" ? i.packageRules = [] : i.editType === "single" && (i.packageRules = [angular.copy(i.defaultSingleRule)]) };
            (function() { i.editType = "single";
                i.onSwitchSku = e;
                i.onSelectSku = o;
                i.onEditTypeChanged = s;
                i.initScrollBar = f })() } } }]);
supplychainModule.controller("SpuEditPackageModalCtrl", ["$scope", "host", "aresNotification", "$modalInstance", "dataDicSvc", "$timeout", function(n, t, i, r, u, f) { "use strict"; var o = function() { n.skus = [{ specAndUnit: "请选择规格" }].concat(t.skus);
            n.existingPackages = t.packages;
            u.systemItemDic.loadActive({ itemType: "库存物品单位" }).then(function(t) { n.units = t });
            n.defaultSku = { id: 0, isLinkedCare: !1, specification: "", unit: "", specAndUnit: "", factoryLocation: "", producerBarCode: "", producerCode: "", code: "", freeField1: "", freeField2: "", freeField3: "", isEnabled: !0 };
            n.defaultSingleRule = { count: 0, fromSku: { specAndUnit: "请选择规格" }, isFromSkuNew: !1, isFromSkuToBeSelected: !0, canSwitchFromSku: !0, toSku: { specAndUnit: "请选择规格" }, isToSkuNew: !1, isToSkuToBeSelected: !0, canSwitchToSku: !0 };
            n.batchConfig = { fromUnit: "", toUnit: "", count: 0 };
            n.packageRules = [angular.copy(n.defaultSingleRule)] },
        s = function() { var t, i = [],
                r, e, o, u, f; return (_.any(n.packageRules, function(r) { if (!r.fromSku.specification || !r.fromSku.unit || !r.toSku.specification || !r.toSku.unit || r.specAndUnit === "请选择规格") return t = "请选择或填写规格名称和单位", !0; if (!r.count) return t = "请填写拆包数量", !0; var u = !1; return r.isFromSkuNew && (u = _.find(n.skus, function(n) { return n.specification === r.fromSku.specification && n.unit === r.fromSku.unit }), u) ? (t = "规格单位【" + r.fromSku.specification + "(" + r.fromSku.unit + ")】已存在，不能新建", !0) : r.isToSkuNew && (u = _.find(n.skus, function(n) { return n.specification === r.toSku.specification && n.unit === r.toSku.unit }), u) ? (t = "规格单位【" + r.toSku.specification + "(" + r.toSku.unit + ")】已存在，不能新建", !0) : r.fromSku.specification === r.toSku.specification && r.fromSku.unit === r.toSku.unit ? (t = "相同规格单位不能进行拆包", !0) : r.fromSku.unit === r.toSku.unit ? (t = "相同单位不能进行拆包", !0) : _.any(n.existingPackages, function(n) { return n.fromSpecification === r.fromSku.specification && n.fromUnit === r.fromSku.unit && n.toSpecification === r.toSku.specification && n.toUnit === r.toSku.unit }) ? (t = "拆包规则已存在", !0) : (i.push([r.fromSku.specification, r.fromSku.unit, r.toSku.specification, r.toSku.unit].join("&&")), i.push([r.toSku.specification, r.toSku.unit, r.fromSku.specification, r.fromSku.unit].join("&&")), !1) }), t) ? t : (_.each(n.existingPackages, function(n) { i.push([n.fromSpecification, n.fromUnit, n.toSpecification, n.toUnit].join("&&"));
                i.push([n.toSpecification, n.toUnit, n.fromSpecification, n.fromUnit].join("&&")) }), r = _.reduce(i, function(n, t, r) { return i.indexOf(t) !== r && n.indexOf(t) < 0 && n.push(t), n }, []), r.length > 0 && (e = r[0].split("&&")[0] + "(" + r[0].split("&&")[1] + ")", o = r[0].split("&&")[2] + "(" + r[0].split("&&")[3] + ")", t = "【" + e + "】和【" + o + "】存在互相拆包规则，请修改"), t) ? t : (u = _.map(n.packageRules, function(n) { return n.fromSku.specAndUnit }).concat(_.pluck(n.existingPackages, "fromSpecAndUnit")), f = _.find(u, function(n, t) { return u.indexOf(n) !== t }), f && (t = "【" + f + "】作为拆包前规格，不能重复设置拆包规则"), t) },
        h = function() { var f = s(),
                t, u; if (f) { i.error(f); return } t = [];
            u = [];
            _.each(n.packageRules, function(n) { n.isFromSkuNew && t.push(n.fromSku);
                n.isToSkuNew && t.push(n.toSku); var i = { fromProductId: n.fromSku.productId || 0, fromSpecification: n.fromSku.specification, fromUnit: n.fromSku.unit, fromSpecAndUnit: n.fromSku.specification + "(" + n.fromSku.unit + ")", toProductId: n.toSku.productId || 0, toSpecification: n.toSku.specification, toUnit: n.toSku.unit, toSpecAndUnit: n.toSku.specification + "(" + n.toSku.unit + ")", count: n.count };
                u.push(i) });
            r.close({ newSkus: t, newPackages: u }) },
        e = function(t, i) { var r = _.extendOwn(angular.copy(n.defaultSku), t); return r.id = 0, r.isLinkedCare = !1, r.isEnabled = !0, r.unit = i, r.specAndUnit = r.specification + "(" + r.unit + ")", r.barCode = null, r },
        c = function() { var t; if (!n.batchConfig.fromUnit) { i.error("请选择或填写拆包前规则"); return } if (!n.batchConfig.toUnit) { i.error("请选择或填写拆包后规则"); return } var o = _.pluck(n.existingPackages, "fromSpecAndUnit"),
                u = _.filter(n.skus, function(t) { return t.unit === n.batchConfig.fromUnit && o.indexOf(t.specAndUnit) < 0 }),
                r = _.filter(n.skus, function(t) { return t.unit === n.batchConfig.toUnit && o.indexOf(t.specification + "(" + n.batchConfig.fromUnit + ")") < 0 }); if (u.length === 0 && r.length === 0) { i.error("现有规格单位中不存在可设置拆包规则的【" + n.batchConfig.fromUnit + "】和【" + n.batchConfig.toUnit + "】单位"); return } t = [];
            u.length > 0 ? _.each(u, function(i) { var u = _.find(r, function(t) { return t.specification === i.specification && t.unit === n.batchConfig.toUnit }),
                    f;
                u ? t.push({ count: n.batchConfig.count, fromSku: i, isFromSkuNew: !1, isFromSkuToBeSelected: !1, canSwitchFromSku: !1, toSku: u, isToSkuNew: !1, isToSkuToBeSelected: !1, canSwitchToSku: !0 }) : (f = e(i, n.batchConfig.toUnit), t.push({ count: n.batchConfig.count, fromSku: i, isFromSkuNew: !1, isFromSkuToBeSelected: !1, canSwitchFromSku: !1, toSku: f, isToSkuNew: !0, isToSkuToBeSelected: !1, canSwitchToSku: !0 })) }) : _.each(r, function(i) { var u = _.find(r, function(t) { return t.specification === i.specification && t.unit === n.batchConfig.fromUnit }),
                    f;
                u ? t.push({ count: n.batchConfig.count, fromSku: u, isFromSkuNew: !1, isFromSkuToBeSelected: !1, canSwitchFromSku: !0, toSku: i, isToSkuNew: !1, isToSkuToBeSelected: !1, canSwitchToSku: !1 }) : (f = e(i, n.batchConfig.fromUnit), t.push({ count: n.batchConfig.count, fromSku: f, isFromSkuNew: !0, isFromSkuToBeSelected: !1, canSwitchFromSku: !0, toSku: i, isToSkuNew: !1, isToSkuToBeSelected: !1, canSwitchToSku: !1 })) });
            n.packageRules = t;
            f(function() { n.initScrollBar() }) };
    (function() { o();
        n.save = h;
        n.createBatchRules = c;
        n.generateNewSku = e })() }]);
supplychainModule.directive("spuPlatformImportDialogView", ["$log", "$timeout", "$window", "$modal", "aresNotification", "dataDicSvc", "officeUtil", "loginContext", function(n, t, i) { return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-platform-import-dialog/spu-platform-import-dialog-view.html", link: function(n, t) { "use strict"; var f = { scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } },
                s = function(t) { var i = window.event ? t.keyCode : t.which;
                    i === 13 && (n.nextPageIndex = 1, n.search()) },
                h = function() { n.nextPageIndex = 1;
                    n.search() },
                u = function() { var r = angular.element(i).height(),
                        n = t.find(".category-menu-tree"),
                        u = t.closest(".content-container").offset().top;
                    n.height(r - u - 82);
                    n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar(f) },
                c = function() { u() },
                l = function(t) { n.selectedCategory = t;
                    n.nextPageIndex = 1;
                    n.search() },
                r = t.find(".spu-product-unity-list-body"),
                e = function() { var u = t.closest(".content-container").offset().top;
                    r.height(angular.element(i).height() - u - 50);
                    r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar(_.extend({}, f, { callbacks: { whileScrolling: function(t) { t.topPct >= 90 && n.nextPageIndex !== -1 && n.search() } } })) },
                a = function() { r.data("mCustomScrollbarIndex") && r.mCustomScrollbar("scrollTo", "top") },
                o = function() { u();
                    e() };
            (function() { n.onEnter = s;
                n.initTreeView = u;
                n.onTreeViewInit = c;
                n.onCategorySelect = l;
                n.initTableScrollbar = e;
                n.onSearchBtnClick = h;
                n.scrollTableToTop = a;
                n.initProductCategoryData().then(function() { n.search() });
                angular.element(i).on("resize", o);
                n.$on("$destroy", function() { angular.element(i).off("resize", o) }) })() } } }]);
supplychainModule.controller("SpuPlatformImportDialogCtrl", ["$log", "$scope", "$modalInstance", "$timeout", "$q", "productUnitySvc", "dataDicSvc", "aresTreeViewUtil", "inventoryUtil", "host", "productUtil", function(n, t, i, r, u, f, e, o, s, h, c) { "use strict"; var v = function() { var n = u.defer(); return e.productPlatformCategoryDic.load().then(function(i) { var r = {};
                _.each(i, function(n) { r[n.id] = n;
                    _.isString(n.levelCode) && (n.levelCode.length === 6 && (n.spriteCssClass = "iconfont icon-wenjianjia"), n.levelCode.length === 9 && (n.spriteCssClass = "iconfont icon-icon-test")) });
                t.categoryTreeData = o.unflatten(i, "showOrder");
                n.resolve(!0) }), n.promise },
        l = !1,
        y = function() { if (t.nextPageIndex !== -1 && !l) { l = !0; var n = { pageIndex: t.nextPageIndex, pageSize: 20, searchText: t.searchKeywords };
                t.selectedCategory && (n.categoryIds = s.getAllSubCategoriesIds(t.selectedCategory));
                t.nextPageIndex === 1 && (t.productUnityList = []);
                f.searchPlatformProduct(n).success(function(n) { t.productUnityList = t.productUnityList.concat(n.items);
                    r(function() { t.initTableScrollbar();
                        t.nextPageIndex === 1 && t.scrollTableToTop();
                        t.nextPageIndex = n.pageCount === n.pageIndex ? -1 : n.pageIndex + 1;
                        l = !1 }) }) } },
        a = function(n) { var t = u.defer(); return f.getFullPltSpu(n.barCode).success(function(n) { t.resolve(n) }), t.promise },
        p = function(n) { a(n).then(function(n) { i.close(n) }) },
        w = function() { var n = u.defer(),
                t = function(r) { var u = {};
                    r.data && r.data.currentSpu && (u = r.data.currentSpu, i.off("CURRENT_SPU_UPDATE", t));
                    n.resolve(u) };
            i.on("CURRENT_SPU_UPDATE", t); return i.broadcast("CURRENT_SPU_REQUEST", {}), n.promise },
        b = function(n) { u.all([a(n), w()]).then(function(n) { var t = n[0],
                    r = n[1];
                c.openReplacePlatformSpuDialog(t, r).then(function(n) { i.close(n) }) }) };
    (function() { t.action = h.action;
        t.selectedCategory = null;
        t.search = y;
        t.nextPageIndex = 1;
        t.importSpu = p;
        t.replaceSpu = b;
        t.initProductCategoryData = v })() }]);
supplychainModule.directive("spuPlatformMatchDialogView", ["$log", "$q", "$timeout", "$window", "$modal", function(n, t, i, r) { return { replace: !0, restrict: "E", templateUrl: "/app/supplychain/views/product-unity/dialogs/spu-platform-match-dialog/spu-platform-match-dialog-view.html", link: function(n, t) { "use strict"; var i = t.find(".spu-platform-product-list"),
                u = function() { var u = t.closest(".content-container").offset().top - 82;
                    i.height(angular.element(r).height() - u - 150);
                    i.data("mCustomScrollbarIndex") ? i.mCustomScrollbar("update") : i.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 }, callbacks: { whileScrolling: function(t) { t.topPct >= 90 && n.nextPageIndex !== -1 && n.search() } } }) },
                f = function() { i.data("mCustomScrollbarIndex") && i.mCustomScrollbar("scrollTo", "top") };
            (function() { n.initScrollbar = u;
                n.scrollToTop = f;
                angular.element(r).on("resize", u);
                n.$on("$destroy", function() { angular.element(r).off("resize", u) }) })() } } }]);
supplychainModule.controller("SpuPlatformMatchDialogCtrl", ["$log", "$scope", "$modal", "$timeout", "$q", "productUnitySvc", "dataDicSvc", "$modalInstance", "host", "productUtil", function(n, t, i, r, u, f, e, o, s, h) { "use strict"; var l = function() { if (t.nextPageIndex !== -1 && !t.isSearching) { t.isSearching = !0; var n = { pageIndex: t.nextPageIndex, pageSize: 20, searchText: t.searchText };
                t.selectedCategory && (n.categoryIds = inventoryUtil.getAllSubCategoriesIds(t.selectedCategory));
                f.searchPlatformProduct(n, !0).success(function(n) { t.nextPageIndex === 1 && (t.productUnityList = []); var i = _.filter(n.items, function(n) { return n.isMatchBaseLcSPU });
                    i.length !== n.items.length && (t.nextPageIndex = -1);
                    t.productUnityList = t.productUnityList.concat(i);
                    r(function() { t.initScrollbar && t.initScrollbar();
                        t.isSearching = !1;
                        t.nextPageIndex === 1 && t.scrollToTop();
                        t.nextPageIndex = n.pageCount === n.pageIndex ? -1 : n.pageIndex + 1 }) }) } },
        a = function() { o.on("SPU_NAME_CHANGED", function(n) { if (n && n.data) { var i = n.data.searchText;
                    i ? t.searchText !== i && (t.productUnityList = [], t.searchText = i, t.nextPageIndex = 1, t.search()) : (t.searchText = "", t.productUnityList = []) } });
            o.on("SPU_NON_MATCH", function(n) { n && n.data && (t.searchText = n.data.searchText, t.productUnityList = []) }) },
        v = function() { var n = u.defer(),
                t = function(i) { var r = {};
                    i.data && i.data.currentSpu && (r = i.data.currentSpu, o.off("CURRENT_SPU_UPDATE", t));
                    n.resolve(r) };
            o.on("CURRENT_SPU_UPDATE", t); return o.broadcast("CURRENT_SPU_REQUEST", {}), n.promise },
        c = function(n) { var t = u.defer(); return f.getFullPltSpu(n.barCode).success(function(n) { t.resolve(n) }), t.promise },
        y = function(n) { c(n).then(function(n) { t.$modalInstance.close(n) }) },
        p = function(n) { u.all([c(n), v()]).then(function(n) { var i = n[0],
                    r = n[1];
                h.openReplacePlatformSpuDialog(i, r).then(function(n) { t.$modalInstance.close(n) }) }) };
    (function() { t.action = s.action;
        t.isSearching = !1;
        t.searchText = "";
        t.nextPageIndex = 1;
        t.search = l;
        t.importSpu = y;
        t.replaceSpu = p;
        a() })() }]);
supplychainModule.directive("supplierEditView", ["$log", "$timeout", "$rootScope", "dataDicSvc", "aresConfirmDialog", "$window", "aresModalShelf", "aresNotification", function(n, t, i, r, u, f, e) { return { restrict: "E", replace: !0, templateUrl: "/app/supplychain/views/supplier-mgmt/supplier-edit-view.html", link: function(n, r) { var v = r.find(".base-info-tab-container"),
                h = r.find(".paper-info-tab-container"),
                c = r.find("#nature-drop"),
                o, y = function() { l() },
                l = function() { c.css({ width: "180px", height: "32px" });
                    c.kendoDropDownList({ optionLabel: "请选择", dataSource: [{ name: "国有企业" }, { name: "合资企业" }, { name: "民营企业" }, { name: "外资企业" }], dataTextField: "name", dataValueField: "name", value: n.supplier.nature, select: function(t) { n.supplier.nature = this.dataItem(t.item)[this.options.dataValueField] || null } }) },
                p = function() { if (!n.supplier.name) return u.error({ message: "请填写" + n.supplierName + "名称" }), !1; if (!n.isLinkedCare) { if (n.supplier.name.indexOf("领健") > -1) { u.error({ message: "不能创建名称包含领健的" + n.supplierName + "！" }); return } if (n.supplier.name.trim() === "领健") { u.error({ message: "不能创建名称为领健的" + n.supplierName + "！" }); return } } n.supplier.isDisabled = !n.supplier.isEnabled;
                    n.saveSupplier(n.supplier) },
                w = function() {!n.supplier || n.isLinkedCare || n.isNotLcView || (n.supplier.isEnabled = !n.supplier.isEnabled) },
                b = function(t) { n.selectTab = t },
                s = function(n) { t(function() { n.height(angular.element(f).height() - 170);
                        n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } }) }, 0, !1) },
                k = function(n, t, i) { i.splice(t, 1) },
                d = function() { r.on("click", ".trigger-modify-btn", function() { angular.element(this).closest(".picture-edit-common-ele").find(".modify-btn").click() }) },
                g = function(n) { if (!o || o.destroyed) { var t = n == 1 ? "厂商导入" : "厂商匹配";
                        o = e.open({ title: t, template: "<dental-lab-factory-select-view><\/dental-lab-factory-select-view>", controller: "DentalLabFactorySelectCtrl", resolve: { dataHost: function() { return { type: n } } } }) } },
                a;
            i.$on("factory_select_add", function(t, i) { var r = {};
                i.type == 1 && (r = { name: i.name, isEnabled: i.enabled, nature: i.companyType, contactName: i.contactPerson, contactPhoneNumber: i.contactTel, contactEmail: i.contactMail, address: i.address, notes: i.notes });
                n.code = i.id;
                _.extend(n.supplier, r);
                l() });
            a = function() { var t = "您确定解除绑定“" + n.supplier.name + "”？解除绑定后，此加工厂将收不到技加工单，在保存后生效";
                    u.confirm({ message: t }).then(function() { n.supplier.code = "" }, function() {}) },
                function() { n.selectTab = "baseInfo";
                    n.setEnable = w;
                    n.save = p;
                    n.setTabActive = b;
                    n.removeImg = k;
                    n.paperTabContainer = h;
                    n.initBasicTabScrollbar = s;
                    n.importTo = g;
                    s(v);
                    s(h);
                    d();
                    n.$watch("supplier", function() { n.supplier && y() });
                    n.unBind = a }() } } }]);
supplychainModule.directive("supplierListView", ["$log", "$q", "$timeout", "$window", "aresModalShelf", "lcUploadUtil", "aresConfirmDialog", function(n, t, i, r, u, f, e) { return { restrict: "E", templateUrl: "/app/supplychain/views/supplier-mgmt/supplier-list-view.html", controller: "SupplierListCtrl", link: function(n, t) { var s = function(t) { n.enableStatus = n.enableStatus ? (n.enableStatus & t) == t ? n.enableStatus - t : n.enableStatus + t : t;
                    n.search() },
                h = function() { o(); var n = angular.element(r);
                    t.find(".supplier-paged-list .main-div").mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 150, advanced: { updateOnContentResize: !0 } });
                    n.on("resize", function() { o() }) },
                o = function() { var i = angular.element(r).height(),
                        u = i - 245,
                        f = +u - 0 - (window.Ares3 ? 20 : 0),
                        n = t.find(".supplier-paged-list .main-div");
                    n.height(f);
                    n.mCustomScrollbar("update");
                    t.find('[data-toggle="tooltip"]').tooltip({ container: ".ares-supplier-main-content" }) },
                c = function() { i(function() { t.find(".supplier-paged-list .main-div").mCustomScrollbar("scrollTo", "top") }, 100) },
                l = function(n) { u.open({ template: "<supplier-quotation-list-modal-view><\/supplier-quotation-list-modal-view>", controller: "SupplierQuotationListModalCtrl", title: "物品报价单：" + n.name, titleIconClass: "iconfont icon-baojiadan", resolve: { host: function() { return { supplierId: n.id, supplierName: n.name, supplierType: n.type } } } }) },
                a = function() { var r = t.find("#supplier-import"),
                        i = new f.UploadUtil({ url: "api/v1/organization/parse-excel", acceptFileTypes: /(\.|\/)(xls|xlsx)$/i }, r);
                    i.register(f.eventNames.done, function(t, i) { i.result && (e.warn({ message: i.result }), n.search()) });
                    f.popUploadInfo(i);
                    t.find("#upload-button").on("click", function() { t.find("#supplier-import").click() }) };
            (function() { n.listHeight = { height: angular.element(window).height() - 245 - (window.Ares3 ? 20 : 0) };
                n.setEnableStatus = s;
                n.initTableView = o;
                n.scrollToTop = c;
                n.showSupplierQuotation = l;
                h();
                a() })() } } }]);
var inventory;
(function() { var n = function() {
        function n(n) { var t = this;
            this.$timeout = n;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/supplier-mgmt/supplier-quotation-edit-modal/supplier-quotation-edit-modal-view.html";
            this.link = function(n, i) { var r = i.find(".supplier-quotation-edit-table"),
                    u = function() { t.$timeout(function() { r.height(i.parent().height() - (n.isEdit ? 75 : 125));
                            r.data("mCustomScrollbarIndex") ? r.mCustomScrollbar("update") : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } });
                            i.find('[data-toggle="tooltip"]').tooltip({ container: ".supplier-quotation-edit-table" }) }, 0, !1) },
                    f = function(n) { n ? t.$timeout(function() { var i = r.find('tr[data-product-id="' + n + '"]').find("input");
                            i.length > 0 && (i.focus(), angular.isFunction(i[0].select) && i[0].select(), t.$timeout(function() { r.mCustomScrollbar("scrollTo", 'tr[data-product-id="' + n + '"]') }, 200)) }, 0, !1) : i.find(".sku-auto-complete-selector-view").find("input").focus() };
                (function() { n.updateScrollbar = u;
                    n.focusNextInput = f })() } } return n.$inject = ["$timeout"], n }();
    supplychainModule.directive("supplierQuotationEditModalView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { var n = function() {
        function n(n, t, i, r, u, f, e, o) { var s = this,
                h;
            this.$scope = n;
            this.$modalInstance = t;
            this.host = i;
            this.$shelfInstance = r;
            this.productSvc = u;
            this.aresNotification = f;
            this.eventAggregator = e;
            this.inventoryUtil = o;
            this.removeSkuIds = [];
            n.skuAutoCompleteOptions = { mode: "quotation", isLinkedCare: null };
            n.currentSupplier = i.currentSupplier;
            n.isOfficePreferredDealerEnabled = i.isOfficePreferredDealerEnabled;
            n.isEdit = i.isEdit;
            n.uiState = { isSetPreferred: !1, skuSelectModal: null, allowInsideCode: !1 };
            n.spuList = n.isEdit ? [i.currentSpu] : [];
            t.on("SKU_SELECT_ADD", function(n) { n && n.data && s.addSkuToList(n.data.sku) });
            t.on("SPU_BATCH_ADD", function(n) { n && n.data && s.addSpusToList(n.data.spus) });
            t.on("TAB_SWITCHED", function() { var n = [];
                s.$scope.spuList.forEach(function(t) { t.products.forEach(function(t) { n.push(t.productId) }) });
                s.$modalInstance.broadcast("SKU_EXIST_LIST", { productIds: n }) });
            this.initBaseData();
            h = n.$watch("updateScrollbar", function(t) { t && (n.updateScrollbar(), h()) }) } return n.prototype.initBaseData = function() { var n = this;
            this.inventoryUtil.getProductCodeOptions().then(function(t) { n.$scope.uiState.allowInsideCode = t.allowInsideCode }) }, n.prototype.addSkuToList = function(n, t) { var i, r;
            t === void 0 && (t = !0);
            i = _.find(this.$scope.spuList, function(t) { return t.id === n.productUnityId });
            i || (i = { id: n.productUnityId, name: n.name, producer: n.producer, preferredDealerId: null, preferredDealerName: null, products: [] }, this.$scope.spuList.push(i));
            _.find(i.products, function(t) { return t.productId === n.id }) || (r = { id: 0, productUnityId: n.productUnityId, productId: n.id, preferredDealerId: 0, preferredDealerName: "", price: 0, name: n.name, specification: n.specification, unit: n.unit, code: n.code, isEnabled: n.isEnabled, producer: n.producer }, i.products.push(r), this.$modalInstance.broadcast("SKU_SELECT_ADDED", { productId: r.productId }));
            i.preferredDealerId === null && this.getPreferredSupplier(i);
            t && (this.$scope.updateScrollbar(), this.$scope.focusNextInput(n.id)) }, n.prototype.addSpusToList = function(n) { var t = this;
            n.forEach(function(n) { n.products.forEach(function(n) { t.addSkuToList(n, !1) }) });
            this.$scope.updateScrollbar() }, n.prototype.onPriceInputKeyUp = function(n) {
            (n.keyCode === 13 || n.key === "Enter") && this.$scope.focusNextInput() }, n.prototype.getPreferredSupplier = function(n) { this.productSvc.getProductDealers(n.products[0].productId).success(function(t) { n.preferredDealerId = t[0].preferredDealerId;
                n.preferredDealerName = t[0].preferredDealerName }) }, n.prototype.save = function() { var n = this,
                t, i;
            this.$scope.spuList.length === 0 && this.aresNotification.error("请添加报价");
            t = [];
            this.$scope.spuList.forEach(function(i) { i.products.forEach(function(r) { t.push({ id: r.id || 0, dealerId: n.$scope.currentSupplier.id, dealerName: n.$scope.currentSupplier.name, preferredDealerId: n.$scope.uiState.isSetPreferred ? n.$scope.currentSupplier.id : i.preferredDealerId, preferredDealerName: n.$scope.uiState.isSetPreferred ? n.$scope.currentSupplier.name : i.preferredDealerName, productId: r.productId, productUnityId: r.productUnityId, price: r.price, name: r.name }) }) });
            i = function() { t.length === 0 ? (n.aresNotification.success("保存成功"), n.$modalInstance.close()) : n.productSvc.saveBatchProductDealers(t).success(function() { n.aresNotification.success("保存成功");
                    n.$modalInstance.close() }).error(function() { n.aresNotification.error("操作失败") }) };
            this.removeSkuIds && this.removeSkuIds.length > 0 ? this.productSvc.deleteBatchProductDealers(this.removeSkuIds).success(function() { i() }).error(function() { n.aresNotification.error("操作失败") }) : i() }, n.prototype.openSkuSelectModal = function(n) { var i = this,
                t = function() { i.$modalInstance.broadcast("SWITCH_SKU_SELECT_TYPE", { type: "singleSpu", spuId: n.id }) };
            this.$scope.uiState.skuSelectModal && !this.$scope.uiState.skuSelectModal.destroyed ? t() : (this.$scope.uiState.skuSelectModal = this.$shelfInstance.open({ title: "添加规格", template: "<sku-select-view><\/sku-select-view>", controller: "SkuSelectCtrl", resolve: { host: function() { return { type: "singleSpu" } } } }), this.$scope.uiState.skuSelectModal.rendered.then(function() { t() })) }, n.prototype.removeSku = function(n, t) { var i = n.products[t];
            n.products.splice(t, 1);
            n.products.length !== 0 || this.$scope.isEdit || (this.$scope.spuList = this.$scope.spuList.filter(function(t) { return t.id !== n.id }));
            this.$modalInstance.broadcast("SKU_SELECT_REMOVED", { productId: i.productId });
            i.id && this.removeSkuIds.push(i.id) }, n.prototype.showProductDetailPopover = function(n, t) { this.eventAggregator.publish(this.eventAggregator.events.ProductSelected, { productId: n.products[0].productId, isSpu: !0 }, t.delegateTarget) }, n.$inject = ["$scope", "$modalInstance", "host", "$shelfInstance", "productSvc", "aresNotification", "eventAggregator", "inventoryUtil"], n }();
    supplychainModule.controller("SupplierQuotationEditModalCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));
var inventory;
(function() { var n = function() {
        function n(n) { var t = this;
            this.$timeout = n;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/supplychain/views/supplier-mgmt/supplier-quotation-list-modal/supplier-quotation-list-modal-view.html";
            this.link = function(n, i) { var r = i.find(".main-content-table"),
                    u = function() { t.$timeout(function() { r.height(i.parent().height() - 110);
                            r.data("mCustomScrollbarIndex") ? (r.mCustomScrollbar("update"), t.$timeout(function() { r.mCustomScrollbar("scrollTo", 0) }, 200, !1)) : r.mCustomScrollbar({ scrollButtons: { enable: !1 }, autoHideScrollbar: !0, scrollInertia: 300, advanced: { updateOnContentResize: !0, autoScrollOnFocus: !1 } });
                            i.find('[data-toggle="tooltip"]').tooltip({ container: ".main-content-table" }) }, 0, !1) };
                (function() { n.updateScrollbar = u })() } } return n.$inject = ["$timeout"], n }();
    supplychainModule.directive("supplierQuotationListModalView", Ares.tsDirective(n)) })(inventory || (inventory = {}));
var inventory;
(function() { var n = function() {
        function n(n, t, i, r, u, f, e, o, s, h, c, l, a, v) { var y = this,
                p;
            this.$scope = n;
            this.host = t;
            this.$timeout = i;
            this.inventoryUtil = r;
            this.aresTreeViewUtil = u;
            this.aresModalShelf = f;
            this.productSvc = e;
            this.officeOptionSvc = o;
            this.enums = s;
            this.aresNotification = h;
            this.aresConfirmDialog = c;
            this.eventAggregator = l;
            this.officeUtil = a;
            this.permissionProvider = v;
            n.selectedCategory = { id: 0, name: "全部分类" };
            n.categoriesTree = [];
            n.uiState = { enabledChecked: !0, disabledChecked: !1, checkAll: !1, allowInsideCode: !1, canEdit: !1, showExport: !1, isLinkedCare: t.supplierType === this.enums.OrganizationType.LinkedCare || t.supplierType === this.enums.OrganizationType.MallDealer };
            n.currentSupplier = { id: t.supplierId, name: t.supplierName, type: t.supplierType };
            n.searchCriteria = { searchText: "", categoryIds: [], isEnabled: null, dealerId: t.supplierId, pageIndex: 0 };
            p = n.$watch("updateScrollbar", function(n) { n && (y.initBaseData(), y.search(), p()) }) } return n.prototype.initBaseData = function() { var n = this;
            this.inventoryUtil.getProductCategories().then(function(t) { var i = n.aresTreeViewUtil.unflatten(t, "showOrder");
                i.unshift(n.$scope.selectedCategory);
                n.$scope.categoriesTree = i });
            this.inventoryUtil.getProductCodeOptions().then(function(t) { n.$scope.uiState.allowInsideCode = t.allowInsideCode });
            this.officeUtil.isRootGroup().then(function(t) { n.$scope.uiState.canEdit = t && n.permissionProvider.isAllowed("product.productInfo") && n.$scope.currentSupplier.type == n.enums.OrganizationType.NormalDealer;
                n.$scope.uiState.showExport = t && n.permissionProvider.isAllowed("product.productInfo") });
            this.officeOptionSvc.getOfficeOption(this.officeOptionSvc.optionKeys.IsOfficePreferredDealerEnabled).then(function(t) { n.$scope.isOfficePreferredDealerEnabled = t }) }, n.prototype.search = function(n) { var i = this,
                t = this.$scope.uiState; if (t.enabledChecked && t.disabledChecked) this.$scope.searchCriteria.isEnabled = null;
            else if (t.enabledChecked && !t.disabledChecked) this.$scope.searchCriteria.isEnabled = 1;
            else if (!t.enabledChecked && t.disabledChecked) this.$scope.searchCriteria.isEnabled = 0;
            else if (!t.enabledChecked && !t.disabledChecked) { this.$scope.quotationList = [];
                this.$scope.page = { size: 10, index: 1, totalCount: 0 }; return } this.$scope.searchCriteria.pageIndex = n ? 1 : this.$scope.page ? this.$scope.page.index : 1;
            this.productSvc.searchProductDealers(this.$scope.searchCriteria).success(function(n) { var t = _.groupBy(n.items, "productUnityId");
                i.$scope.quotationList = _.map(_.values(t), function(n) { var t = n[0]; return { id: t.productUnityId, name: t.name, preferredDealerId: t.preferredDealerId, preferredDealerName: t.preferredDealerName, producer: t.producer, checked: !1, products: n } });
                i.$scope.page = { size: 10, index: n.pageIndex, totalCount: n.totalCount };
                i.$scope.updateScrollbar();
                i.resetUIState() }) }, n.prototype.export = function() { var n, t, i;
            this.initSearchCriteria();
            n = [{ field: "code", hidden: !1, title: "内部编码", width: "150px" }, { field: "barCode", hidden: !1, title: "商城编码", width: "150px" }, { field: "name", hidden: !1, title: "名称", width: "250px" }, { field: "producer", hidden: !1, title: "品牌", width: "150px" }, { field: "specification", hidden: !1, title: "规格", width: "150px" }, { field: "unit", hidden: !1, title: "单位", width: "150px" }, { field: "price", hidden: !1, title: "售价", width: "150px" }, { field: "isNotAgreedProduct", hidden: !1, title: "是否协议价", width: "150px" }, { field: "isPreferred", hidden: !1, title: "是否首选", width: "150px" }, ];
            this.$scope.currentSupplier.type == this.enums.OrganizationType.NormalDealer && (n = _.filter(n, function(n) { return n.field != "barCode" && n.field != "isNotAgreedProduct" }));
            this.$scope.isOfficePreferredDealerEnabled && (n = _.filter(n, function(n) { return n.field != "isPreferred" }));
            t = angular.copy(this.$scope.searchCriteria);
            i = { criteria: t, columns: n };
            this.productSvc.exportProductDealers(i) }, n.prototype.initSearchCriteria = function() { this.$scope.searchCriteria.isEnabled = this.$scope.uiState.enabledChecked && this.$scope.uiState.disabledChecked || !this.$scope.uiState.enabledChecked && !this.$scope.uiState.disabledChecked ? null : this.$scope.uiState.enabledChecked && !this.$scope.uiState.disabledChecked ? 1 : 0;
            this.$scope.searchCriteria.pageIndex = this.$scope.page ? this.$scope.page.index : 0 }, n.prototype.toggleCheckAll = function() { var n = this;
            this.$scope.quotationList.forEach(function(t) { t.checked = n.$scope.uiState.checkAll }) }, n.prototype.onSpuChecked = function(n) { this.$scope.uiState.checkAll = n.checked ? _.every(this.$scope.quotationList, function(n) { return n.checked }) : !1 }, n.prototype.batchSetPreferred = function() { var n = this,
                i = 0,
                t = []; if (this.$scope.quotationList.forEach(function(n) { n.checked && (t = t.concat(n.products), i++) }), t.length === 0) { this.aresNotification.error("请先选择物品"); return } this.aresConfirmDialog.confirm({ message: '已选择 <span class="enyo-text-warning">' + i + "<\/span> 个物品<br>\n                          是否确定设置 " + this.$scope.currentSupplier.name + " 为首选供应商？" }).then(function() { var i = t.map(function(t) { return { id: t.id, dealerId: n.$scope.currentSupplier.id, dealerName: n.$scope.currentSupplier.name, productId: t.productId, productUnityId: t.productUnityId, preferredDealerId: n.$scope.currentSupplier.id, preferredDealerName: n.$scope.currentSupplier.name, price: t.price } });
                n.productSvc.saveBatchProductDealers(i).success(function() { n.aresNotification.success("保存成功");
                    n.$scope.uiState.checkAll = !1;
                    n.search() }) }) }, n.prototype.batchDelete = function() { var n = this,
                i = 0,
                t = []; if (this.$scope.quotationList.forEach(function(n) { n.checked && (t = t.concat(n.products), i++) }), t.length === 0) { this.aresNotification.error("请先选择物品"); return } this.aresConfirmDialog.confirm({ message: '已选择 <span class="enyo-text-warning">' + i + "<\/span> 个物品<br>\n                          是否确定删除报价？" }).then(function() { var i = t.map(function(n) { return n.id });
                n.productSvc.deleteBatchProductDealers(i).success(function() { n.aresNotification.success("删除成功");
                    n.$scope.uiState.checkAll = !1;
                    n.search() }) }) }, n.prototype.deleteSpu = function(n) { var t = this;
            this.aresConfirmDialog.confirm({ message: '是否确定删除 <span class="enyo-text-warning">' + n.name + "<\/span> 的报价？" }).then(function() { var i = n.products.map(function(n) { return n.id });
                t.productSvc.deleteBatchProductDealers(i).success(function() { t.aresNotification.success("删除成功");
                    t.$scope.uiState.checkAll = !1;
                    t.search() }) }) }, n.prototype.showProductDetailPopover = function(n, t) { this.eventAggregator.publish(this.eventAggregator.events.ProductSelected, { productId: n.products[0].productId, isSpu: !0 }, t.delegateTarget) }, n.prototype.showAgreePriceLabell = function(n, t) { return this.$scope.uiState.isLinkedCare && !t.isNotAgreedProduct && t.price > 0 }, n.prototype.onProductCategoryChange = function(n) { if (n.id) { var t = [],
                    i = function(n) { t.push(n.id);
                        n.items && n.items.forEach(function(n) { i(n) }) };
                i(n);
                this.$scope.searchCriteria.categoryIds = t } else this.$scope.searchCriteria.categoryIds = [];
            this.search(!0) }, n.prototype.openEditModal = function(n) { var t = this,
                i = !!n,
                r = this.aresModalShelf.open({ title: "新增物品报价单", titleIconClass: "iconfont icon-bianji", template: "<supplier-quotation-edit-modal-view><\/supplier-quotation-edit-modal-view>", controller: "SupplierQuotationEditModalCtrl", needActive: !0, resolve: { host: function() { return { currentSupplier: t.$scope.currentSupplier, isEdit: i, currentSpu: angular.copy(n), isOfficePreferredDealerEnabled: t.$scope.isOfficePreferredDealerEnabled } } }, confirmClose: !0 });
            r.result.then(function() { t.search() }) }, n.prototype.onSearchBoxKeyUp = function(n) {
            (n.keyCode === this.enums.KeyCode.Enter || n.key === "Enter") && this.search(!0) }, n.prototype.resetUIState = function() { this.$scope.uiState.checkAll = !1;
            this.$scope.$apply() }, n.$inject = ["$scope", "host", "$timeout", "inventoryUtil", "aresTreeViewUtil", "aresModalShelf", "productSvc", "officeOptionSvc", "enums", "aresNotification", "aresConfirmDialog", "eventAggregator", "officeUtil", "permissionProvider"], n }();
    supplychainModule.controller("SupplierQuotationListModalCtrl", Ares.tsController(n)) })(inventory || (inventory = {}));